package com.ship.dispatch.service.orderPay.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.ship.common.core.enums.CorporateType;
import com.ship.common.core.enums.OrderStatus;
import com.ship.common.core.enums.OrderType;
import com.ship.common.business.service.impl.BaseServiceImpl;
import com.ship.common.core.exception.BusException;
import com.ship.common.core.web.domain.BaseResultCode;
import com.ship.dispatch.bean.ConShipping;
import com.ship.dispatch.bean.SpDispatchSchemeExecute;
import com.ship.dispatch.bean.fob.SpFobFileRecord;
import com.ship.dispatch.bean.orderPay.*;
import com.ship.dispatch.bean.sys.SysConstant;
import com.ship.dispatch.bo.orderPay.SpPaymentOrderBO;
import com.ship.dispatch.bo.orderPay.SpPaymentOrderDetailBO;
import com.ship.dispatch.bpm.service.ProcessInstanceService;
import com.ship.dispatch.mapper.ConShippingMapper;
import com.ship.dispatch.mapper.fob.SpFobFileRecordMapper;
import com.ship.dispatch.mapper.orderPay.*;
import com.ship.dispatch.mapper.sys.SysConstantMapper;
import com.ship.dispatch.model.dto.orderPay.SpPaymentOrderDetailDto;
import com.ship.dispatch.model.dto.orderPay.SpPaymentOrderDto;
import com.ship.dispatch.service.SpDispatchSchemeExecuteService;
import com.ship.dispatch.service.orderPay.SpFundPayManageDetailService;
import com.ship.dispatch.service.orderPay.SpPaymentOrderService;
import com.ship.dispatch.util.IDUtil;
import com.ship.common.security.utils.SecurityUtils;
import com.ship.dispatch.util.constant.OrderPayConstants;
import com.ship.dispatch.vo.orderPay.*;
import com.ship.system.api.BpmInstanceService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

import static com.ship.common.core.enums.OrderType.*;

@Service
public class SpPaymentOrderServiceImpl extends BaseServiceImpl<SpPaymentOrderMapper, SpPaymentOrder> implements SpPaymentOrderService {
    private static final Logger logger = LoggerFactory.getLogger(SpPaymentOrderServiceImpl.class);

    @Autowired
    private SysConstantMapper constantMapper;
    @Autowired
    @Lazy
    private SpDispatchSchemeExecuteService dispatchSchemeExecuteService;
    @Autowired
    private ConShippingAgencyMapper conShippingAgencyMapper;
    @Autowired
    private ConInsuranceGoodsMapper conInsuranceGoodsMapper;
    @Autowired
    private ConThirdPartyMeasurementMapper conThirdPartyMeasurementMapper;
    @Autowired
    private ConShippingMapper conShippingMapper;
    @Autowired
    private ConRefuelingMapper conRefuelingMapper;
    @Autowired
    private ConInsurancePeopleMapper conInsurancePeopleMapper;
    @Autowired
    private SpPaymentOrderDetailMapper orderDetailMapper;
    @Autowired
    private SpFobFileRecordMapper fileRecordMapper;
    @Autowired
    private ConFilesMapper conFilesMapper;
    @Autowired
    private PayFundManagementMapper payFundManagementMapper;
    @Autowired
    private SpFundManageMapper spFundManageMapper;
    @Autowired
    private SpFundManageDetailMapper spFundManageDetailMapper;

    @Autowired
    private SpFundPayManageDetailService spFundPayManageDetailService;

    /**
     * 根据航次号和订单类型获取上传发票时间
     *
     * @param dispatchSchemeExecuteId 航次号id
     * @param orderType               订单类型id
     * @param contractId              合同id
     * @return
     */
    @Override
    public String getInvoiceTime(Long dispatchSchemeExecuteId, Integer orderType, Long contractId) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String invoiceTime = "";
        Date payEndTIme = null;
        SpDispatchSchemeExecute dispatchSchemeExecute = dispatchSchemeExecuteService.getById(dispatchSchemeExecuteId);
        if (null != dispatchSchemeExecute) {
            //预付款时间（天）
            Integer advancePayDays = 0;
            //预付款时间类型1:工作日，2：自然日
            Integer advancePayType = 0;
            //结算时间（天）
            Integer payDays = 0;
            //结算时间类型1:工作日，2：自然日
            Integer payDaysType = 0;
            if (orderType.equals(OrderType.LOADING_PORT_PAY.getCode())) {
                ConShippingAgency conShippingAgency = conShippingAgencyMapper.selectById(contractId);
                if (null != conShippingAgency) {
                    advancePayDays = conShippingAgency.getAdvancePayDays();
                    advancePayType = conShippingAgency.getAdvancePayDayType();
                }
                payEndTIme = dispatchSchemeExecute.getExpectedLoadingDate();
                if (advancePayDays > 0) {
                    payEndTIme = getPayEndTimeByWeekday(payEndTIme, advancePayDays, advancePayType);
                }
            } else if (orderType.equals(OrderType.UNLOADING_PORT_PAY.getCode())) {
                ConShippingAgency conShippingAgency = conShippingAgencyMapper.selectById(contractId);
                if (null != conShippingAgency) {
                    advancePayDays = conShippingAgency.getAdvancePayDays();
                    advancePayType = conShippingAgency.getAdvancePayDayType();
                }
                payEndTIme = dispatchSchemeExecute.getExpectedUnloadingWindow();
                if (advancePayDays > 0) {
                    payEndTIme = getPayEndTimeByWeekday(payEndTIme, advancePayDays, advancePayType);
                }
            } else if (orderType.equals(OrderType.FUEL_DELIVERY_SETTLE.getCode())
                    || orderType.equals(OrderType.FUEL_RETURN_SETTLE.getCode())) {
                ConRefueling conRefueling = conRefuelingMapper.selectById(contractId);
                if (null != conRefueling) {
                    payDays = conRefueling.getPayDays();
                    payDaysType = conRefueling.getPayDaysType();
                }
                //加油（燃油）
                if (payDays > 0) {
                    payEndTIme = getPayEndTimeByWeekday(payEndTIme, payDays, payDaysType);
                }
            }
            if (null != payEndTIme) {
                invoiceTime = formatter.format(payEndTIme);
            }
        }
        return invoiceTime;
    }

    /**
     * 通过指定时间、往后延期几天、天数类型获得支付时间（这个方法有bug：没有判断如果是工作日延期过程中有周六、周日）
     *
     * @param payEndTime     任意时间
     * @param advancePayDays 延期天数
     * @param advancePayType 天数类型（1：工作日，2：自然日）
     * @return
     */
    private Date getPayEndTimeByWeekday(Date payEndTime, Integer advancePayDays, Integer advancePayType) {
        Instant instant = payEndTime.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDate payEndTimeLocalDate = instant.atZone(zoneId).toLocalDate();
        payEndTimeLocalDate = payEndTimeLocalDate.minusDays(advancePayDays);
//        payEndTimeLocalDate = payEndTimeLocalDate.plusDays(3);
//        DayOfWeek dayOfWeek1 = payEndTimeLocalDate.getDayOfWeek();
//        if (dayOfWeek1.getValue() > 5) {
//            System.out.println("经过了周末");
//        } else {
//            System.out.println("未经过周末");
//        }
        //如果是工作日则判断，不是工作日不判断
        if (advancePayType > 0 && advancePayType.equals(1)) {
            //判断是否是工作日  如果需要判断节假日查看辅助工具：6tail/lunar-java
            DayOfWeek dayOfWeek = DayOfWeek.of(payEndTimeLocalDate.get(ChronoField.DAY_OF_WEEK));
            switch (dayOfWeek) {
                case SUNDAY:
                    payEndTimeLocalDate = payEndTimeLocalDate.minus(2, ChronoUnit.DAYS);
                case SATURDAY:
                    payEndTimeLocalDate = payEndTimeLocalDate.minus(1, ChronoUnit.DAYS);
            }
        }
        ZonedDateTime zdt = payEndTimeLocalDate.atStartOfDay(zoneId);
        payEndTime = Date.from(zdt.toInstant());
        return payEndTime;
    }

    /**
     * 获取字典表类型
     *
     * @param labelName 名称
     * @return
     */
    @Override
    public List<SysConstant> getConstantsByType(String labelName) {
        List<SysConstant> constants = new ArrayList<>();
        constants = constantMapper.selectList(
                new LambdaQueryWrapper<SysConstant>()
                        .likeRight(StringUtils.isNotBlank(labelName),SysConstant::getConstLabel, labelName)
                        .eq(SysConstant::getType, OrderPayConstants.ORDER_PAY_TYPE)
        );
        return constants;
    }

    public SysConstant getNewConstant(String labelName){
        SysConstant constants = constantMapper.selectOne(
                new LambdaQueryWrapper<SysConstant>()
                        .eq(SysConstant::getConstLabel, labelName)
                        .eq(SysConstant::getType, OrderPayConstants.ORDER_PAY_TYPE)
                        .last("limit 1")
        );
        if(constants != null){
            return constants;
        }
        SysConstant newData = constantMapper.selectOne(
                new LambdaQueryWrapper<SysConstant>()
                        .eq(SysConstant::getType, OrderPayConstants.ORDER_PAY_TYPE)
                        .orderByDesc(SysConstant::getConstValue)
                        .last("limit 1")
        );
        SysConstant saveData = new SysConstant();
        saveData.setType(OrderPayConstants.ORDER_PAY_TYPE);
        saveData.setConstLabel(labelName);
        saveData.setConstValue(newData == null ? 1 : (newData.getConstValue() + 1));
        constantMapper.insert(saveData);
        return saveData;
    }


    /**
     * 获取订单类型
     *
     * @param labelName 名称
     * @return
     */
    @Override
    public List<OrderTypesVO> getOrderTypes(String labelName) {
        List<OrderTypesVO> orderTypesVOS = new ArrayList<>();
        List<SysConstant> constants = this.getConstantsByType(labelName);
        if (null != constants && constants.size() > 0) {
            constants.stream().forEach(c -> {
                OrderTypesVO orderTypesVO = new OrderTypesVO();
                orderTypesVO.setConstLabel(c.getConstLabel());
                orderTypesVO.setConstValue(c.getConstValue());
                orderTypesVOS.add(orderTypesVO);
            });
        }
        return orderTypesVOS;
    }

    /**
     * 获取航次号
     *
     * @return
     */
    @Override
    public List<SpDispatchSchemeExecuteVO> getVoyageNos() {
        List<SpDispatchSchemeExecuteVO> spDispatchSchemeExecuteVOS = new ArrayList<>();
        List<SpDispatchSchemeExecute> dispatchSchemeExecutes = dispatchSchemeExecuteService.list();
        if (null != dispatchSchemeExecutes && dispatchSchemeExecutes.size() > 0) {
            dispatchSchemeExecutes.stream().forEach(d -> {
                SpDispatchSchemeExecuteVO spDispatchSchemeExecuteVO = new SpDispatchSchemeExecuteVO();
                BeanUtils.copyProperties(d, spDispatchSchemeExecuteVO);
                spDispatchSchemeExecuteVOS.add(spDispatchSchemeExecuteVO);
            });
        }
        return spDispatchSchemeExecuteVOS;
    }

    /**
     * 根据订单类型查询合同信息
     *
     * @param constValue 订单类型
     * @return
     */
    @Override
    public List<ContractsVO> getContracts(Integer constValue) {
        List<ContractsVO> contractsVOS = new ArrayList<>();
        if (null != constValue) {
            switch (constValue) {
                case 1:
                case 2:
                case 3:
                case 4:
                    //船舶代理合同
                    List<ConShippingAgency> conShippingAgencies = conShippingAgencyMapper.selectList(
                            new LambdaQueryWrapper<ConShippingAgency>()
                                    .orderByDesc(ConShippingAgency::getCreateDate)
                    );
                    if (null != conShippingAgencies && conShippingAgencies.size() > 0) {
                        conShippingAgencies.stream().forEach(c -> {
                            ContractsVO contractsVO = new ContractsVO();
                            BeanUtils.copyProperties(c, contractsVO);
                            contractsVO.setContractType(1);
                            contractsVOS.add(contractsVO);
                        });
                    }
                    break;
                case 5:
                    //人险
                    List<ConInsurancePeople> conInsurancePeoples = conInsurancePeopleMapper.selectList(
                            new LambdaQueryWrapper<ConInsurancePeople>()
                                    .orderByDesc(ConInsurancePeople::getCreateDate)
                    );
                    if (null != conInsurancePeoples && conInsurancePeoples.size() > 0) {
                        conInsurancePeoples.stream().forEach(c -> {
                            ContractsVO contractsVO = new ContractsVO();
                            BeanUtils.copyProperties(c, contractsVO);
                            contractsVO.setContractType(6);
                            contractsVOS.add(contractsVO);
                        });
                    }
                    break;
                case 6:
                    //保险合同（货险）
                    List<ConInsuranceGoods> conInsuranceGoods = conInsuranceGoodsMapper.selectList(
                            new LambdaQueryWrapper<ConInsuranceGoods>()
                                    .orderByDesc(ConInsuranceGoods::getCreateDate)
                    );
                    if (null != conInsuranceGoods && conInsuranceGoods.size() > 0) {
                        conInsuranceGoods.stream().forEach(c -> {
                            ContractsVO contractsVO = new ContractsVO();
                            BeanUtils.copyProperties(c, contractsVO);
                            contractsVO.setContractType(2);
                            contractsVOS.add(contractsVO);
                        });
                    }
                    break;
                case 7:
                case 8:
                    //第三方计量合同
                    List<ConThirdPartyMeasurement> conThirdPartyMeasurements = conThirdPartyMeasurementMapper.selectList(
                            new LambdaQueryWrapper<ConThirdPartyMeasurement>()
                                    .orderByDesc(ConThirdPartyMeasurement::getCreateDate)
                    );
                    if (null != conThirdPartyMeasurements && conThirdPartyMeasurements.size() > 0) {
                        conThirdPartyMeasurements.stream().forEach(c -> {
                            ContractsVO contractsVO = new ContractsVO();
                            BeanUtils.copyProperties(c, contractsVO);
                            contractsVO.setContractType(3);
                            contractsVOS.add(contractsVO);
                        });
                    }
                    break;
                case 9:
                case 10:
                case 11:
                case 12:
                case 13:
                case 14:
                case 15:
                    //租金相关合同、还船费、交船费、LNG 底角结算相关--船运合同
                    List<ConShipping> conShippings = conShippingMapper.selectList(
                            new LambdaQueryWrapper<ConShipping>()
                                    .orderByDesc(ConShipping::getCreateDate)
                    );
                    if (null != conShippings && conShippings.size() > 0) {
                        conShippings.stream().forEach(c -> {
                            ContractsVO contractsVO = new ContractsVO();
                            BeanUtils.copyProperties(c, contractsVO);
                            contractsVO.setContractType(4);
                            contractsVOS.add(contractsVO);
                        });
                    }
                    break;
//                case 12:
//                    //交船费
//                    break;
//                case 13:
//                    //还船费
//                    break;
//                case 14:
//                case 15:
//                    //LNG 底角结算相关
//                    break;
                case 16:
                case 17:
                    //燃油结算相关--加油合同
                    List<ConRefueling> conRefuelings = conRefuelingMapper.selectList(
                            new LambdaQueryWrapper<ConRefueling>()
                                    .orderByDesc(ConRefueling::getCreateDate)
                    );
                    if (null != conRefuelings && conRefuelings.size() > 0) {
                        conRefuelings.stream().forEach(c -> {
                            ContractsVO contractsVO = new ContractsVO();
                            BeanUtils.copyProperties(c, contractsVO);
                            contractsVO.setContractType(5);
                            contractsVOS.add(contractsVO);
                        });
                    }
                    break;
            }
        } else {
            //获取所有合同
            contractsVOS.addAll(this.getAllContracts());
        }
        return contractsVOS;
    }

    /**
     * 获取所有类型合同
     *
     * @return
     */
    private List<ContractsVO> getAllContracts() {
        List<ContractsVO> contractsVOS = new ArrayList<>();
        //船舶代理合同
        List<ConShippingAgency> conShippingAgencies = conShippingAgencyMapper.selectList(
                new LambdaQueryWrapper<ConShippingAgency>()
                        .orderByDesc(ConShippingAgency::getCreateDate)
        );
        if (null != conShippingAgencies && conShippingAgencies.size() > 0) {
            conShippingAgencies.stream().forEach(c -> {
                ContractsVO contractsVO = new ContractsVO();
                BeanUtils.copyProperties(c, contractsVO);
                contractsVO.setContractType(1);
                contractsVOS.add(contractsVO);
            });
        }
        //保险合同（货险）
        List<ConInsuranceGoods> conInsuranceGoods = conInsuranceGoodsMapper.selectList(
                new LambdaQueryWrapper<ConInsuranceGoods>()
                        .orderByDesc(ConInsuranceGoods::getCreateDate)
        );
        if (null != conInsuranceGoods && conInsuranceGoods.size() > 0) {
            conInsuranceGoods.stream().forEach(c -> {
                ContractsVO contractsVO = new ContractsVO();
                BeanUtils.copyProperties(c, contractsVO);
                contractsVO.setContractType(2);
                contractsVOS.add(contractsVO);
            });
        }
        //人险
        List<ConInsurancePeople> conInsurancePeoples = conInsurancePeopleMapper.selectList(
                new LambdaQueryWrapper<ConInsurancePeople>()
                        .orderByDesc(ConInsurancePeople::getCreateDate)
        );
        if (null != conInsurancePeoples && conInsurancePeoples.size() > 0) {
            conInsurancePeoples.stream().forEach(c -> {
                ContractsVO contractsVO = new ContractsVO();
                BeanUtils.copyProperties(c, contractsVO);
                contractsVO.setContractType(6);
                contractsVOS.add(contractsVO);
            });
        }
        //第三方计量合同
        List<ConThirdPartyMeasurement> conThirdPartyMeasurements = conThirdPartyMeasurementMapper.selectList(
                new LambdaQueryWrapper<ConThirdPartyMeasurement>()
                        .orderByDesc(ConThirdPartyMeasurement::getCreateDate)
        );
        if (null != conThirdPartyMeasurements && conThirdPartyMeasurements.size() > 0) {
            conThirdPartyMeasurements.stream().forEach(c -> {
                ContractsVO contractsVO = new ContractsVO();
                BeanUtils.copyProperties(c, contractsVO);
                contractsVO.setContractType(3);
                contractsVOS.add(contractsVO);
            });
        }
        //租金相关合同--船运合同
        List<ConShipping> conShippings = conShippingMapper.selectList(
                new LambdaQueryWrapper<ConShipping>()
                        .orderByDesc(ConShipping::getCreateDate)
        );
        if (null != conShippings && conShippings.size() > 0) {
            conShippings.stream().forEach(c -> {
                ContractsVO contractsVO = new ContractsVO();
                BeanUtils.copyProperties(c, contractsVO);
                contractsVO.setContractType(4);
                contractsVOS.add(contractsVO);
            });
        }
        //燃油结算相关--加油合同
        List<ConRefueling> conRefuelings = conRefuelingMapper.selectList(
                new LambdaQueryWrapper<ConRefueling>()
                        .orderByDesc(ConRefueling::getCreateDate)
        );
        if (null != conRefuelings && conRefuelings.size() > 0) {
            conRefuelings.stream().forEach(c -> {
                ContractsVO contractsVO = new ContractsVO();
                BeanUtils.copyProperties(c, contractsVO);
                contractsVO.setContractType(5);
                contractsVOS.add(contractsVO);
            });
        }
        return contractsVOS;
    }

    /**
     * 新增订单
     *
     * @param spPaymentOrderDto 订单dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean savePayOrder(SpPaymentOrderDto spPaymentOrderDto) {
        Boolean judge = false;
        Date payEndTime = spPaymentOrderDto.getPayEndTime();
        SpPaymentOrder paymentOrder = new SpPaymentOrder();
        paymentOrder.setId(IDUtil.nextId());
        paymentOrder.setOrderTypeText(spPaymentOrderDto.getOrderTypeText());
        paymentOrder.setContractId(spPaymentOrderDto.getContractId());
        paymentOrder.setPayAmount(spPaymentOrderDto.getPayAmount());
        paymentOrder.setPayAmountUnit(spPaymentOrderDto.getPayAmountUnit());
        paymentOrder.setOrderStatus(1);
        paymentOrder.setOrderRemark(spPaymentOrderDto.getOrderRemark());
        paymentOrder.setCreateBy(SecurityUtils.getUsername());
        paymentOrder.setCreateDate(new Date());
        paymentOrder.setApplicantPeople(SecurityUtils.getUsername());
        paymentOrder.setOrderSynchronous(2);
        paymentOrder.setPayEndTime(payEndTime);

        //将手动维护的订单类型更新到字典里面去
        SysConstant constant = this.getNewConstant(spPaymentOrderDto.getOrderTypeText());
        paymentOrder.setOrderType(constant.getConstValue());
        paymentOrder.setOrderTypeText(constant.getConstLabel());

        //结算时间（天）
        //Integer payDays = 0;
        //结算时间类型1:工作日，2：自然日
        //Integer payDaysType = 0;
        List<ContractsVO> contractsVOS = this.getAllContracts();
        if (null != contractsVOS && contractsVOS.size() > 0) {
            if (null != spPaymentOrderDto.getContractId()) {
                contractsVOS = contractsVOS.stream().filter(c -> c.getId().equals(spPaymentOrderDto.getContractId())).collect(Collectors.toList());
                if (contractsVOS.size() > 0) {
                    paymentOrder.setContractType(contractsVOS.get(0).getContractType());
                    paymentOrder.setContractName(contractsVOS.get(0).getContractName());
                    //payDays = contractsVOS.get(0).getPayDays();
                    //payDaysType = contractsVOS.get(0).getPayDaysType();
                    //赋值合同地址
                    List<ConFiles> conFiles = conFilesMapper.getConFilesByConIdAndFileType(contractsVOS.get(0).getId(), 1);
                    if (null != conFiles && conFiles.size() > 0) {
                        paymentOrder.setContractAddress(conFiles.get(0).getUrl());
                    }
                }
            }
        }

        //新增明细
        SpPaymentOrderDetailBO spPaymentOrderDetailBO = new SpPaymentOrderDetailBO();
        if(null != spPaymentOrderDto.getVoyageId()){
            SpDispatchSchemeExecute dispatchSchemeExecute = dispatchSchemeExecuteService.getById(spPaymentOrderDto.getVoyageId());
            if (null != dispatchSchemeExecute) {
                //费用支付截止日期
                //尾款
//                if (paymentOrder.getOrderType().equals(LOADING_PORT_PAY_END.getCode())
//                        || paymentOrder.getOrderType().equals(OrderType.UNLOADING_PORT_PAY_END.getCode())) {
//                    if (payDays > 0) {
//                        payEndTime = getPayEndTimeByWeekday(payEndTime, payDays, payDaysType);
//                    }
//                } else if (paymentOrder.getOrderType().equals(LOADING_PORT_THIRD_PARTY.getCode())
//                        || paymentOrder.getOrderType().equals(UNLOADING_PORT_THIRD_PARTY.getCode())) {
//                    //第三方计量
//                    if (payDays > 0) {
//                        payEndTime = getPayEndTimeByWeekday(payEndTime, payDays, payDaysType);
//                    }
//                } else if (paymentOrder.getOrderType().equals(OrderType.CARGO_INSURANCE.getCode())) {
//                    //货险
//                    payEndTime = getPayEndTimeByWeekday(payEndTime, 7, 1);
//                }
                //payEndTime = this.getPayEndTime(dispatchSchemeExecute.getExpectedLoadingDate(), spPaymentOrderDto.getPayEndTime(), spPaymentOrderDto.getConstValue(), dispatchSchemeExecute.getUploadInvoiceTime(), dispatchSchemeExecute.getLoadInvoiceTime());
                //paymentOrder.setPayEndTime(payEndTime);
                //String voyageNo = dispatchSchemeExecute.getVoyageNo().replaceAll("\\-", "");
                paymentOrder.setVoyageNo(dispatchSchemeExecute.getVoyageNo());

                //构建明细
                spPaymentOrderDetailBO.setOrderId(paymentOrder.getId());
                spPaymentOrderDetailBO.setPayableAmount(paymentOrder.getPayAmount());
                if ("1".equals(dispatchSchemeExecute.getTradeBody())) {
                    spPaymentOrderDetailBO.setCnoocCorporation("CNOOC Gas and Power Trading& Marketing Limited");
                } else {
                    spPaymentOrderDetailBO.setCnoocCorporation("CNOOC Gas and Power Singapore Trading& Marketing Pte. Ltd");
                }
                spPaymentOrderDetailBO.setShipName(dispatchSchemeExecute.getShipName());
                spPaymentOrderDetailBO.setExpectedLoadingPort(dispatchSchemeExecute.getExpectedLoadingPort());
                spPaymentOrderDetailBO.setExpectedLoadingDate(dispatchSchemeExecute.getExpectedLoadingDate());
                spPaymentOrderDetailBO.setExpectedUnloadingDate(dispatchSchemeExecute.getExpectedUnloadingWindow());
                spPaymentOrderDetailBO.setExpectedUnloadingPort(dispatchSchemeExecute.getExpectedUnloadingPort());
            }
        }else{
            //构建明细
            spPaymentOrderDetailBO.setOrderId(paymentOrder.getId());
            spPaymentOrderDetailBO.setPayableAmount(paymentOrder.getPayAmount());
        }

        //生成订单编号
        SpPaymentOrder order = this.getOne(new LambdaQueryWrapper<SpPaymentOrder>()
                .likeRight(SpPaymentOrder::getPayOrderNumber,"QT-")
                .orderByDesc(SpPaymentOrder::getCreateDate)
                .last("limit 1"));
        if(null != order){
            String numberStr = order.getPayOrderNumber();
            if(StringUtils.isNotBlank(numberStr)){
                Integer orderNum = Integer.valueOf(numberStr.split("-")[1]);
                orderNum++;
                paymentOrder.setPayOrderNumber("QT-"+orderNum);
            }
        }else{
            paymentOrder.setPayOrderNumber("QT-1");
        }
        //新增订单
        judge = this.save(paymentOrder);
        //新增订单明细
        this.saveOrderDetail(spPaymentOrderDetailBO);

        //同步合同信息
        this.synchronousContract(paymentOrder);

        return judge;
    }

    /**
     * 获取截止支付时间
     *
     * @param loadingDate       装载时间
     * @param payEndTime        截止支付时间
     * @param constValue        订单类型
     * @param uploadInvoiceTime 上传发票时间-卸载港船代尾款
     * @param loadInvoiceTime   上传发票时间-装载港船代尾款
     * @return
     */
    private Date getPayEndTime(Date loadingDate, Date payEndTime, Integer constValue, Date uploadInvoiceTime, Date loadInvoiceTime) {
        if (null != constValue) {
            if (constValue.equals(1) || constValue.equals(3)) {
                //支付时间应为预计装载时间前 3 个工作日
                Instant instant = loadingDate.toInstant();
                ZoneId zoneId = ZoneId.systemDefault();
                LocalDate payEndTimeLocalDate = instant.atZone(zoneId).toLocalDate();
                payEndTimeLocalDate = payEndTimeLocalDate.minusDays(3);
                //判断是否是工作日  如果需要判断节假日查看辅助工具：6tail/lunar-java
                DayOfWeek dayOfWeek = DayOfWeek.of(payEndTimeLocalDate.get(ChronoField.DAY_OF_WEEK));
                switch (dayOfWeek) {
                    case SUNDAY:
                        payEndTimeLocalDate = payEndTimeLocalDate.minus(2, ChronoUnit.DAYS);
                    case SATURDAY:
                        payEndTimeLocalDate = payEndTimeLocalDate.minus(1, ChronoUnit.DAYS);
                }

                ZonedDateTime zdt = payEndTimeLocalDate.atStartOfDay(zoneId);
                payEndTime = Date.from(zdt.toInstant());
            }
            if (constValue.equals(2)) {
                //支付时间应为上传发票后的 40 天
                if (null != loadInvoiceTime) {
                    payEndTime = DateUtil.offsetDay(loadInvoiceTime, 40);
                }
            }
            if (constValue.equals(4)) {
                //支付时间应为上传发票后的 40 天
                if (null != uploadInvoiceTime) {
                    payEndTime = DateUtil.offsetDay(uploadInvoiceTime, 40);
                }
            }
        }
        return payEndTime;
    }

    /**
     * 获取订单编号
     *
     * @param constValue
     * @param voyageNo
     * @return
     */
    private String getPayOrderNumber(String voyageNo, Integer constValue) {
        if (StringUtils.isEmpty(voyageNo)) {
            Calendar cal = Calendar.getInstance();
            int year = cal.get(Calendar.YEAR);
            voyageNo = "CNOOC" + year;
        }
        String payOrderNumber = "";
        if (null != constValue) {
            switch (constValue) {
                case 1:
                case 2:
                case 3:
                case 4:
                    payOrderNumber = getOrderNumberString(voyageNo, payOrderNumber, "CD");
                    break;
                case 5:
                case 6:
                    payOrderNumber = getOrderNumberString(voyageNo, payOrderNumber, "BX");
                    break;
                case 7:
                case 8:
                    payOrderNumber = getOrderNumberString(voyageNo, payOrderNumber, "MSC");
                    break;
                case 9:
                case 10:
                case 11:
                    payOrderNumber = getOrderNumberString(voyageNo, payOrderNumber, "TCP");
                    break;
                case 12:
                    payOrderNumber = getOrderNumberString(voyageNo, payOrderNumber, "P");
                    break;
                case 13:
                    payOrderNumber = getOrderNumberString(voyageNo, payOrderNumber, "B");
                    break;
                case 14:
                case 15:
                    payOrderNumber = getOrderNumberString(voyageNo, payOrderNumber, "Heel");
                    break;
                case 16:
                case 17:
                    payOrderNumber = getOrderNumberString(voyageNo, payOrderNumber, "Fuel");
                    break;
                case 18:
                    payOrderNumber = getOrderNumberString(voyageNo, payOrderNumber, "TCP");
                    break;
            }
        }
        return payOrderNumber;
    }

    private String getOrderNumberString(String voyageNo, String payOrderNumber, String identifying) {
        voyageNo = voyageNo.replaceAll("\\-", "");
        SpPaymentOrder paymentOrder = this.getBaseMapper().getMaxPayOrderNumber(identifying);
        if (null != paymentOrder) {
            String numStr = paymentOrder.getPayOrderNumber().substring(paymentOrder.getPayOrderNumber().lastIndexOf('-') + 1);
            if (StringUtils.isNotBlank(numStr)) {
                Integer num = Integer.valueOf(numStr) + 1;
                payOrderNumber = String.format(voyageNo + "-%s-%s", identifying, num);
            }
        } else {
            payOrderNumber = String.format(voyageNo + "-%s-1", identifying);
        }
        return payOrderNumber;
    }

    /**
     * 燃油台账同步订单，生成订单编号
     * @param identifying
     * @return
     */
    private String getOrderNumberStringByFuel(String identifying) {
        String payOrderNumber = "";
        SpPaymentOrder paymentOrder = this.getBaseMapper().getMaxPayOrderNumber(identifying);
        if (null != paymentOrder) {
            String numStr = paymentOrder.getPayOrderNumber().substring(paymentOrder.getPayOrderNumber().lastIndexOf('-') + 1);
            if (StringUtils.isNotBlank(numStr)) {
                Integer num = Integer.valueOf(numStr) + 1;
                payOrderNumber = String.format("%s-%s", identifying, num);
            }
        } else {
            payOrderNumber = String.format("%s-1", identifying);
        }
        return payOrderNumber;
    }

    @Resource
    ProcessInstanceService processInstanceService;

    /**
     * 删除支付结算
     *
     * @param id
     * @return
     */
    public Boolean removePayOrder(Long id) {
        Boolean judge = false;
        SpPaymentOrder paymentOrder = this.getById(id);
        if (null != paymentOrder) {
            if(null !=paymentOrder.getApproverStatus()){
                if (paymentOrder.getApproverStatus() == 0) {
                    throw new BusException("当前订单已经提交删除申请，请勿重复提交", BaseResultCode.GENERAL_ERROR);
                }
            }
            //开启审批流程
            Map<String, Object> map = new HashMap<>();
            map.put("serviceType", 1);
            map.put("module", "payOrder");
            map.put("moduleName","船舶船员信息");
            String processInstanceId = processInstanceService.createProcessInstance2(BpmInstanceService.SYSTEM_DELETE_BPM_KEY, map, id + "");
            paymentOrder.setProcessInstanceId(processInstanceId);
            paymentOrder.setApproverStatus(0);
            judge = this.updateById(paymentOrder);
        }
        return judge;
    }

    /**
     * 删除合同对应资金结算记录
     * @param orderId
     */
    @Override
    public void removePayFundManagement(Long orderId){
        PayFundManagement fundManagement = payFundManagementMapper.selectOne(new LambdaQueryWrapper<PayFundManagement>().eq(PayFundManagement::getOrderId,orderId));
        if(null != fundManagement){
            payFundManagementMapper.deleteById(fundManagement);
        }
    }

    /**
     * 查询支付结算列表
     *
     * @return
     */
    @Override
    public List<SpPaymentOrderVO> getPayOrders() {
        List<SpPaymentOrderVO> spPaymentOrderVOS = new ArrayList<>();
        List<SpPaymentOrder> paymentOrders = this.list();
        if (null != paymentOrders && paymentOrders.size() > 0) {
            paymentOrders.stream().forEach(p -> {
                SpPaymentOrderVO spPaymentOrderVO = new SpPaymentOrderVO();
                BeanUtils.copyProperties(p, spPaymentOrderVO);
                spPaymentOrderVO.setOrderTypeListForSearch(this.getOrderTypeInfo(p.getOrderType()));
                spPaymentOrderVO.setOrderStatusTypeListForSearch(this.getOrderStatusInfo(p.getOrderStatus()));
                spPaymentOrderVOS.add(spPaymentOrderVO);
            });
        }
        return spPaymentOrderVOS;
    }

    private String getOrderTypeInfo(Integer orderType) {
        String orderTypeStr = "";
        if (orderType.equals(OrderType.LOADING_PORT_PAY.getCode())) {
            orderTypeStr = OrderType.LOADING_PORT_PAY.getInfo();
        } else if (orderType.equals(LOADING_PORT_PAY_END.getCode())) {
            orderTypeStr = LOADING_PORT_PAY_END.getInfo();
        } else if (orderType.equals(OrderType.UNLOADING_PORT_PAY.getCode())) {
            orderTypeStr = OrderType.UNLOADING_PORT_PAY.getInfo();
        } else if (orderType.equals(OrderType.UNLOADING_PORT_PAY_END.getCode())) {
            orderTypeStr = OrderType.UNLOADING_PORT_PAY_END.getInfo();
        } else if (orderType.equals(OrderType.CHARTERER_INSURANCE.getCode())) {
            orderTypeStr = OrderType.CHARTERER_INSURANCE.getInfo();
        } else if (orderType.equals(OrderType.CARGO_INSURANCE.getCode())) {
            orderTypeStr = OrderType.CARGO_INSURANCE.getInfo();
        } else if (orderType.equals(LOADING_PORT_THIRD_PARTY.getCode())) {
            orderTypeStr = LOADING_PORT_THIRD_PARTY.getInfo();
        } else if (orderType.equals(UNLOADING_PORT_THIRD_PARTY.getCode())) {
            orderTypeStr = UNLOADING_PORT_THIRD_PARTY.getInfo();
        } else if (orderType.equals(OrderType.SHIP_RENTAL.getCode())) {
            orderTypeStr = OrderType.SHIP_RENTAL.getInfo();
        } else if (orderType.equals(OrderType.SHIP_NEXT_RENTAL.getCode())) {
            orderTypeStr = OrderType.SHIP_NEXT_RENTAL.getInfo();
        } else if (orderType.equals(OrderType.SHIP_END_RENTAL.getCode())) {
            orderTypeStr = OrderType.SHIP_END_RENTAL.getInfo();
        } else if (orderType.equals(OrderType.DELIVERY_FEE.getCode())) {
            orderTypeStr = OrderType.DELIVERY_FEE.getInfo();
        } else if (orderType.equals(OrderType.RETURN_SHIP_FEE.getCode())) {
            orderTypeStr = OrderType.RETURN_SHIP_FEE.getInfo();
        } else if (orderType.equals(OrderType.LNG_DELIVERY_FEE.getCode())) {
            orderTypeStr = OrderType.LNG_DELIVERY_FEE.getInfo();
        } else if (orderType.equals(OrderType.LNG_RETURN_FEE.getCode())) {
            orderTypeStr = OrderType.LNG_RETURN_FEE.getInfo();
        } else if (orderType.equals(OrderType.FUEL_DELIVERY_SETTLE.getCode())) {
            orderTypeStr = OrderType.FUEL_DELIVERY_SETTLE.getInfo();
        } else if (orderType.equals(OrderType.FUEL_RETURN_SETTLE.getCode())) {
            orderTypeStr = OrderType.FUEL_RETURN_SETTLE.getInfo();
        }
        return orderTypeStr;
    }

    private String getOrderStatusInfo(Integer orderStatus) {
        String orderStatusStr = "";
        if (orderStatus.equals(OrderStatus.UNAUDITE.getCode())) {
            orderStatusStr = OrderStatus.UNAUDITE.getInfo();
        } else if (orderStatus.equals(OrderStatus.AUDITE.getCode())) {
            orderStatusStr = OrderStatus.AUDITE.getInfo();
        } else if (orderStatus.equals(OrderStatus.PAID.getCode())) {
            orderStatusStr = OrderStatus.PAID.getInfo();
        }
        return orderStatusStr;
    }

    /**
     * 船运执行同步到支付结算列表
     */
    @Override
    public SpPaymentOrder synchronousPayOrder(SpPaymentOrderBO paymentOrderBO) {
        SpPaymentOrder spPaymentOrder = new SpPaymentOrder();
        BeanUtils.copyProperties(paymentOrderBO, spPaymentOrder);
        String orderNumber = "";
        if(!paymentOrderBO.getOrderType().equals(FUEL_INJECTION.getCode())){
            orderNumber = this.getPayOrderNumber(paymentOrderBO.getVoyageNo(), paymentOrderBO.getOrderType());
        }else{
            orderNumber = getOrderNumberStringByFuel("Fuel-"+paymentOrderBO.getShipName());
        }
        spPaymentOrder.setPayOrderNumber(orderNumber);
        spPaymentOrder.setCreateBy(SecurityUtils.getUsername());
        spPaymentOrder.setCreateDate(new Date());
        spPaymentOrder.setOrderSynchronous(1);
        if (null != spPaymentOrder.getId()) {
            spPaymentOrder.setId(null);
        }
        spPaymentOrder.setApplicantPeople(SecurityUtils.getUsername());
        spPaymentOrder.setId(IDUtil.nextId());
        this.save(spPaymentOrder);
        //同步合同信息
        this.synchronousContract(spPaymentOrder);

        return spPaymentOrder;
    }

    /**
     * 船运执行同步到支付结算详情
     */
    @Override
    public SpPaymentOrderDetail synchronousPayOrderDetail(SpPaymentOrderDetailBO orderDetailBO) {
        SpPaymentOrderDetail spPaymentOrderDetail = new SpPaymentOrderDetail();
        BeanUtils.copyProperties(orderDetailBO, spPaymentOrderDetail);
        spPaymentOrderDetail.setId(IDUtil.nextId());
        spPaymentOrderDetail.setCreateBy(SecurityUtils.getUsername());
        spPaymentOrderDetail.setCreateDate(new Date());
        spPaymentOrderDetail.setOrderDetailSynchronous(1);
        if (spPaymentOrderDetail.getBalanceAmount() == null) {
            spPaymentOrderDetail.setBalanceAmount(BigDecimal.ZERO);
        }
        orderDetailMapper.insert(spPaymentOrderDetail);

        //更新订单主表的船舶、时间、港口等信息
        if(spPaymentOrderDetail.getOrderId() != null){
            SpPaymentOrder order = this.baseMapper.selectById(spPaymentOrderDetail.getOrderId());
            if(order != null){
                order.setShipName(spPaymentOrderDetail.getShipName());
                order.setExpectedLoadingDate(spPaymentOrderDetail.getExpectedLoadingDate());
                order.setExpectedUnloadingDate(spPaymentOrderDetail.getExpectedUnloadingDate());
                order.setExpectedLoadingPort(spPaymentOrderDetail.getExpectedLoadingPort());
                order.setExpectedUnloadingPort(spPaymentOrderDetail.getExpectedUnloadingPort());
                this.baseMapper.updateById(order);
            }
        }

        return spPaymentOrderDetail;
    }

    private SpPaymentOrderDetail saveOrderDetail(SpPaymentOrderDetailBO orderDetailBO) {
        SpPaymentOrderDetail spPaymentOrderDetail = new SpPaymentOrderDetail();
        BeanUtils.copyProperties(orderDetailBO, spPaymentOrderDetail);
        spPaymentOrderDetail.setId(IDUtil.nextId());
        spPaymentOrderDetail.setCreateBy(SecurityUtils.getUsername());
        spPaymentOrderDetail.setCreateDate(new Date());
        spPaymentOrderDetail.setOrderDetailSynchronous(2);
        if (spPaymentOrderDetail.getBalanceAmount() == null) {
            spPaymentOrderDetail.setBalanceAmount(BigDecimal.ZERO);
        }
        orderDetailMapper.insert(spPaymentOrderDetail);

        //更新订单主表的船舶、时间、港口等信息
        if(spPaymentOrderDetail.getOrderId() != null){
            SpPaymentOrder order = this.baseMapper.selectById(spPaymentOrderDetail.getOrderId());
            if(order != null){
                order.setShipName(spPaymentOrderDetail.getShipName());
                order.setExpectedLoadingDate(spPaymentOrderDetail.getExpectedLoadingDate());
                order.setExpectedUnloadingDate(spPaymentOrderDetail.getExpectedUnloadingDate());
                order.setExpectedLoadingPort(spPaymentOrderDetail.getExpectedLoadingPort());
                order.setExpectedUnloadingPort(spPaymentOrderDetail.getExpectedUnloadingPort());
                this.baseMapper.updateById(order);
            }
        }

        return spPaymentOrderDetail;
    }

    /**
     * 获取支付结算订单详情
     *
     * @return
     */
    @Override
    public SpPaymentOrderDetailVO getSpPaymentOrderDetail(Long orderId) {
        SpPaymentOrder paymentOrder = this.getById(orderId);
        if (paymentOrder == null) {
            return null;
        }
        SpPaymentOrderDetailVO paymentOrderDetailVO = new SpPaymentOrderDetailVO();

        List<SpPaymentOrderDetail> paymentOrderDetails = orderDetailMapper.selectList(new LambdaQueryWrapper<SpPaymentOrderDetail>()
                .eq(SpPaymentOrderDetail::getOrderId, orderId)
        );

        BeanUtils.copyProperties(paymentOrder, paymentOrderDetailVO);
        if(null != paymentOrder.getOrderType()){
            //装载船代预付款/卸载船代预付款展示的信息
            if (paymentOrder.getOrderType().equals(OrderType.LOADING_PORT_PAY.getCode()) || paymentOrder.getOrderType().equals(OrderType.UNLOADING_PORT_PAY.getCode())) {
                AdvanceChargesTitleVO advanceChargesTitleVO = new AdvanceChargesTitleVO();
                List<TableColumnHeaderVO> tableColumnHeaderVOList = new ArrayList<>();
//                tableColumnHeaderVOList.add(new TableColumnHeaderVO("订单详情主键", "id"));
//                tableColumnHeaderVOList.add(new TableColumnHeaderVO("订单id", "orderId"));
                tableColumnHeaderVOList.add(new TableColumnHeaderVO("海油公司", "cnoocCorporation"));
                tableColumnHeaderVOList.add(new TableColumnHeaderVO("船舶代理公司", "shipAgencyCorporation"));
                tableColumnHeaderVOList.add(new TableColumnHeaderVO("船舶名称", "shipName"));
                tableColumnHeaderVOList.add(new TableColumnHeaderVO("预计装载时间", "expectedLoadingDate"));
                if (paymentOrder.getOrderType().equals(OrderType.LOADING_PORT_PAY.getCode())) {
                    tableColumnHeaderVOList.add(new TableColumnHeaderVO("装载港", "expectedLoadingPort"));
                } else {
                    tableColumnHeaderVOList.add(new TableColumnHeaderVO("卸载港", "expectedUnloadingPort"));
                }
                tableColumnHeaderVOList.add(new TableColumnHeaderVO("预付金额", "advancePayAmount"));
                tableColumnHeaderVOList.add(new TableColumnHeaderVO("结余金额", "balanceAmount"));
                tableColumnHeaderVOList.add(new TableColumnHeaderVO("应付金额", "payableAmount"));
                advanceChargesTitleVO.setTableColumnHeaderVOList(tableColumnHeaderVOList);

                if (null != paymentOrderDetails && paymentOrderDetails.size() > 0) {
                    paymentOrderDetails.stream().forEach(p -> {
                        AdvanceChargesVO advanceChargesVO = new AdvanceChargesVO();
                        BeanUtils.copyProperties(p, advanceChargesVO);
                        advanceChargesTitleVO.getInformations().add(advanceChargesVO);
                    });
                }
                paymentOrderDetailVO.getData().add(advanceChargesTitleVO);
            }
            //货险
            if (paymentOrder.getOrderType().equals(OrderType.CARGO_INSURANCE.getCode())) {
                //货险展示的为预保单信息
                AdvancePolicyTitleVO advancePolicyTitleVO = new AdvancePolicyTitleVO();
                List<TableColumnHeaderVO> tableColumnHeaderVOList1 = new ArrayList<>();
//                tableColumnHeaderVOList1.add(new TableColumnHeaderVO("订单详情主键", "id"));
//                tableColumnHeaderVOList1.add(new TableColumnHeaderVO("订单id", "orderId"));
                tableColumnHeaderVOList1.add(new TableColumnHeaderVO("船舶名称", "shipName"));
                tableColumnHeaderVOList1.add(new TableColumnHeaderVO("预计装载时间", "expectedLoadingDate"));
                tableColumnHeaderVOList1.add(new TableColumnHeaderVO("装载港", "expectedLoadingPort"));
                tableColumnHeaderVOList1.add(new TableColumnHeaderVO("预计卸载港", "expectedUnloadingPort"));
                tableColumnHeaderVOList1.add(new TableColumnHeaderVO("预计装货量", "estimateLoadVolume"));
                tableColumnHeaderVOList1.add(new TableColumnHeaderVO("预计货物价格", "estimateGoodsPrice"));
                tableColumnHeaderVOList1.add(new TableColumnHeaderVO("备注", "orderDetailRemark"));
                advancePolicyTitleVO.setTableColumnHeaderVOList(tableColumnHeaderVOList1);

                if (null != paymentOrderDetails && paymentOrderDetails.size() > 0) {
                /*paymentOrderDetails.stream().filter(p->p.getAdvancePolicyInfo().equals("1")).forEach(p -> {
                    AdvancePolicyInformationsVO advancePolicyInformationsVO = new AdvancePolicyInformationsVO();
                    BeanUtils.copyProperties(p, advancePolicyInformationsVO);
                    advancePolicyTitleVO.getInformations().add(advancePolicyInformationsVO);
                });*/

                    for (SpPaymentOrderDetail paymentOrderDetail : paymentOrderDetails) {
                        if (null != paymentOrderDetail.getAdvancePolicyInfo() && paymentOrderDetail.getAdvancePolicyInfo().equals("1")) {
                            AdvancePolicyInformationsVO advancePolicyInformationsVO = new AdvancePolicyInformationsVO();
                            BeanUtils.copyProperties(paymentOrderDetail, advancePolicyInformationsVO);
                            advancePolicyTitleVO.getInformations().add(advancePolicyInformationsVO);
                        }

                    }
                }
                paymentOrderDetailVO.getData().add(advancePolicyTitleVO);
                //货险展示的为实际保单信息
                ActualPolicyTitleVO actualPolicyTitleVO = new ActualPolicyTitleVO();
                List<TableColumnHeaderVO> tableColumnHeaderVOList2 = new ArrayList<>();
//                tableColumnHeaderVOList2.add(new TableColumnHeaderVO("订单详情主键", "id"));
//                tableColumnHeaderVOList2.add(new TableColumnHeaderVO("订单id", "orderId"));
                tableColumnHeaderVOList2.add(new TableColumnHeaderVO("实际装载时间", "realityLoadingDate"));
                tableColumnHeaderVOList2.add(new TableColumnHeaderVO("最大峰值（MMBTU）", "maxPeakValue"));
                tableColumnHeaderVOList2.add(new TableColumnHeaderVO("单价（美元/MMBTU）", "unitPrice"));
                tableColumnHeaderVOList2.add(new TableColumnHeaderVO("投保额", "sumInsure"));
                tableColumnHeaderVOList2.add(new TableColumnHeaderVO("费率", "rate"));
                tableColumnHeaderVOList2.add(new TableColumnHeaderVO("保费合计（美元）", "totalPremiumDollar"));
                tableColumnHeaderVOList2.add(new TableColumnHeaderVO("保费合计（人民币）", "totalPremiumRmb"));
                actualPolicyTitleVO.setTableColumnHeaderVOList(tableColumnHeaderVOList2);

                if (null != paymentOrderDetails && paymentOrderDetails.size() > 0) {
                    for (SpPaymentOrderDetail paymentOrderDetail : paymentOrderDetails) {
                        if (null != paymentOrderDetail.getActualPolicyInfo()
                                && paymentOrderDetail.getActualPolicyInfo().equals("1")) {
                            ActualPolicyInformationsVO actualPolicyInformationsVO = new ActualPolicyInformationsVO();
                            BeanUtils.copyProperties(paymentOrderDetail, actualPolicyInformationsVO);
                            actualPolicyTitleVO.getInformations().add(actualPolicyInformationsVO);
                        }
                    }
                }
                paymentOrderDetailVO.getData().add(actualPolicyTitleVO);
            }
            //装载第三方计量费用/卸载第三方计量费用展示的信息
            if (paymentOrder.getOrderType().equals(LOADING_PORT_THIRD_PARTY.getCode()) || paymentOrder.getOrderType().equals(UNLOADING_PORT_THIRD_PARTY.getCode())) {
                ThirdPartyitleVO thirdPartyitleVO = new ThirdPartyitleVO();
                List<TableColumnHeaderVO> tableColumnHeaderVOList3 = new ArrayList<>();
//                tableColumnHeaderVOList3.add(new TableColumnHeaderVO("订单详情主键", "id"));
//                tableColumnHeaderVOList3.add(new TableColumnHeaderVO("订单id", "orderId"));
                tableColumnHeaderVOList3.add(new TableColumnHeaderVO("海油公司", "cnoocCorporation"));
                tableColumnHeaderVOList3.add(new TableColumnHeaderVO("船舶名称", "shipName"));
                if (paymentOrder.getOrderType().equals(LOADING_PORT_THIRD_PARTY.getCode())) {
                    tableColumnHeaderVOList3.add(new TableColumnHeaderVO("装载港", "expectedLoadingPort"));
                } else {
                    tableColumnHeaderVOList3.add(new TableColumnHeaderVO("卸载港", "expectedUnloadingPort"));
                }
                tableColumnHeaderVOList3.add(new TableColumnHeaderVO("第三方计量公司", "thirdPartyCorporation"));
                tableColumnHeaderVOList3.add(new TableColumnHeaderVO("检验费", "inspectFee"));
                tableColumnHeaderVOList3.add(new TableColumnHeaderVO("备注", "orderDetailRemark"));
                thirdPartyitleVO.setTableColumnHeaderVOList(tableColumnHeaderVOList3);

                if (null != paymentOrderDetails && paymentOrderDetails.size() > 0) {
                    paymentOrderDetails.stream().forEach(p -> {
                        ThirdPartyInformationsVO thirdPartyInformationsVO = new ThirdPartyInformationsVO();
                        BeanUtils.copyProperties(p, thirdPartyInformationsVO);
                        thirdPartyitleVO.getInformations().add(thirdPartyInformationsVO);
                    });
                }
                paymentOrderDetailVO.getData().add(thirdPartyitleVO);
            }
            //装载船代尾款、卸载船代尾款
            if (paymentOrder.getOrderType().equals(LOADING_PORT_PAY_END.getCode()) || paymentOrder.getOrderType().equals(UNLOADING_PORT_PAY_END.getCode())) {
                AdvanceChargesEndTitleVO advanceChargesEndTitleVO = new AdvanceChargesEndTitleVO();
                List<TableColumnHeaderVO> tableColumnHeaderVOList = new ArrayList<>();
                tableColumnHeaderVOList.add(new TableColumnHeaderVO("海油公司", "cnoocCorporation"));
                tableColumnHeaderVOList.add(new TableColumnHeaderVO("船舶代理公司", "shipAgencyCorporation"));
                tableColumnHeaderVOList.add(new TableColumnHeaderVO("船舶名称", "shipName"));
                if (paymentOrder.getOrderType().equals(OrderType.LOADING_PORT_PAY_END.getCode())) {
                    tableColumnHeaderVOList.add(new TableColumnHeaderVO("实际装载时间", "realityLoadingDate"));
                    advanceChargesEndTitleVO.setName("装载" + advanceChargesEndTitleVO.getName());
                    tableColumnHeaderVOList.add(new TableColumnHeaderVO("装载港", "expectedLoadingPort"));
                } else {
                    tableColumnHeaderVOList.add(new TableColumnHeaderVO("实际卸载时间", "realityUnloadingDate"));
                    advanceChargesEndTitleVO.setName("卸载" + advanceChargesEndTitleVO.getName());
                    tableColumnHeaderVOList.add(new TableColumnHeaderVO("卸载港", "expectedUnloadingPort"));
                }
                tableColumnHeaderVOList.add(new TableColumnHeaderVO("预付金额", "advancePayAmount"));
                tableColumnHeaderVOList.add(new TableColumnHeaderVO("实际金额", "balanceAmount"));
                tableColumnHeaderVOList.add(new TableColumnHeaderVO("账户金额·初始", "accountInitialBalance"));
                tableColumnHeaderVOList.add(new TableColumnHeaderVO("实付金额", "paidAmount"));
                tableColumnHeaderVOList.add(new TableColumnHeaderVO("账户金额·更新", "accountBalance"));
                advanceChargesEndTitleVO.setTableColumnHeaderVOList(tableColumnHeaderVOList);

                if (null != paymentOrderDetails && paymentOrderDetails.size() > 0) {
                    paymentOrderDetails.stream().forEach(p -> {
                        AdvanceChargesEndVO advanceChargesEndVO = new AdvanceChargesEndVO();
                        BeanUtils.copyProperties(p, advanceChargesEndVO);
                        advanceChargesEndTitleVO.getInformations().add(advanceChargesEndVO);
                    });
                }
                paymentOrderDetailVO.getData().add(advanceChargesEndTitleVO);
            }
            //燃油台账
            if(paymentOrder.getOrderType().equals(FUEL_INJECTION.getCode())){
                if (null != paymentOrderDetails && paymentOrderDetails.size() > 0) {
                    paymentOrderDetails.stream().forEach(p -> {
                        paymentOrderDetailVO.setShipName(p.getShipName());
                        paymentOrderDetailVO.setRefuelTime(p.getRefuelTime());
                        paymentOrderDetailVO.setVlsfoOilQuantity(p.getVlsfoOilQuantity());
                        paymentOrderDetailVO.setVlsfoOilPrice(p.getVlsfoOilPrice());
                        paymentOrderDetailVO.setLsmgoOilQuantity(p.getLsmgoOilQuantity());
                        paymentOrderDetailVO.setLsmgoOilPrice(p.getLsmgoOilPrice());
                        paymentOrderDetailVO.setFuelSupplier(p.getFuelSupplier());
                    });
                }
            }
        }
        //附件信息集合
        List<SpFobFileRecord> fileRecords = fileRecordMapper.selectList(new LambdaQueryWrapper<SpFobFileRecord>()
                .eq(SpFobFileRecord::getOrderDetailId, paymentOrder.getId())
        );
        List<OrderAttachmentsVO> orderAttachmentsVOS = new ArrayList<>();
        if (null != fileRecords && fileRecords.size() > 0) {
            fileRecords.stream().forEach(f -> {
                OrderAttachmentsVO orderAttachmentsVO = new OrderAttachmentsVO();
                BeanUtils.copyProperties(f, orderAttachmentsVO);
                orderAttachmentsVOS.add(orderAttachmentsVO);
            });
            paymentOrderDetailVO.setOrderAttachmentsVOS(orderAttachmentsVOS);
        }
        return paymentOrderDetailVO;
    }

    /**
     * 编辑支付结算订单详情
     *
     * @return
     */
    // @Transactional
    @Override
    public SpPaymentOrderDetailVO updateSpPaymentOrderDetail(SpPaymentOrderDetailDto paymentOrderDetailDto) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SpPaymentOrderDetailVO paymentOrderDetailVO = new SpPaymentOrderDetailVO();

        SpPaymentOrder paymentOrder = this.getById(paymentOrderDetailDto.getId());

        //更新支付结算订单信息
        if (null != paymentOrder) {
            BeanUtils.copyProperties(paymentOrderDetailDto, paymentOrderDetailVO);
            paymentOrder.setOrderStatus(paymentOrderDetailDto.getOrderStatus());
            this.updateById(paymentOrder);
        }

        //更新支付结算订单详情信息
        if (null != paymentOrderDetailDto.getData()) {
            paymentOrderDetailDto.getData().stream().forEach(d -> {
                if (null != ((LinkedHashMap) d).get("id")) {
                    String id = ((LinkedHashMap) d).get("id").toString();
                    //更新装载船代预付款/卸载船代预付款相关集合列表
                    if (id.equals("a1")) {
                        if (null != ((LinkedHashMap) d).get("informations")) {
                            List advanceChargesVOS = ((ArrayList) ((LinkedHashMap) d).get("informations"));
                            if (null != advanceChargesVOS && advanceChargesVOS.size() > 0) {
                                for (int i = 0; i < advanceChargesVOS.size(); i++) {
                                    SpPaymentOrderDetail paymentOrderDetail = new SpPaymentOrderDetail();
                                    paymentOrderDetail.setId(Long.valueOf(((LinkedHashMap) advanceChargesVOS.get(i)).get("id").toString()));
                                    paymentOrderDetail.setOrderId(Long.valueOf(((LinkedHashMap) advanceChargesVOS.get(i)).get("orderId").toString()));
                                    if (null != ((LinkedHashMap) advanceChargesVOS.get(i)).get("cnoocCorporation")) {
                                        paymentOrderDetail.setCnoocCorporation(((LinkedHashMap) advanceChargesVOS.get(i)).get("cnoocCorporation").toString());
                                    }
                                    if (null != ((LinkedHashMap) advanceChargesVOS.get(i)).get("shipAgencyCorporation")) {
                                        paymentOrderDetail.setShipAgencyCorporation(((LinkedHashMap) advanceChargesVOS.get(i)).get("shipAgencyCorporation").toString());
                                    }
                                    if (null != ((LinkedHashMap) advanceChargesVOS.get(i)).get("shipName")) {
                                        paymentOrderDetail.setShipName(((LinkedHashMap) advanceChargesVOS.get(i)).get("shipName").toString());
                                    }
                                    if (null != ((LinkedHashMap) advanceChargesVOS.get(i)).get("expectedLoadingDate")) {
                                        try {
                                            paymentOrderDetail.setExpectedLoadingDate(sdf.parse(((LinkedHashMap) advanceChargesVOS.get(i)).get("expectedLoadingDate").toString()));
                                        } catch (ParseException e) {
                                            throw new RuntimeException(e);
                                        }
                                    }
                                    if (null != ((LinkedHashMap) advanceChargesVOS.get(i)).get("expectedLoadingPort")) {
                                        paymentOrderDetail.setExpectedLoadingPort(((LinkedHashMap) advanceChargesVOS.get(i)).get("expectedLoadingPort").toString());
                                    }
                                    if (null != ((LinkedHashMap) advanceChargesVOS.get(i)).get("expectedUnloadingPort")) {
                                        paymentOrderDetail.setExpectedUnloadingPort(((LinkedHashMap) advanceChargesVOS.get(i)).get("expectedUnloadingPort").toString());
                                    }
                                    if (null != ((LinkedHashMap) advanceChargesVOS.get(i)).get("advancePayAmount")) {
                                        paymentOrderDetail.setAdvancePayAmount(new BigDecimal(((LinkedHashMap) advanceChargesVOS.get(i)).get("advancePayAmount").toString()));
                                    }
                                    if (null != ((LinkedHashMap) advanceChargesVOS.get(i)).get("balanceAmount")) {
                                        paymentOrderDetail.setBalanceAmount(new BigDecimal(((LinkedHashMap) advanceChargesVOS.get(i)).get("balanceAmount").toString()));
                                    }
                                    if (null != ((LinkedHashMap) advanceChargesVOS.get(i)).get("payableAmount")) {
                                        paymentOrderDetail.setPayableAmount(new BigDecimal(((LinkedHashMap) advanceChargesVOS.get(i)).get("payableAmount").toString()));
                                    }
                                    orderDetailMapper.updateById(paymentOrderDetail);
                                }
                            }
                        }
                    }
                    //更新货险相关--预保单信息集合列表
                    if (id.equals("a2")) {
                        if (null != ((LinkedHashMap) d).get("informations")) {
                            List advancePolicyTitleVOS = ((ArrayList) ((LinkedHashMap) d).get("informations"));
                            if (null != advancePolicyTitleVOS && advancePolicyTitleVOS.size() > 0) {
                                for (int i = 0; i < advancePolicyTitleVOS.size(); i++) {
                                    SpPaymentOrderDetail paymentOrderDetail = new SpPaymentOrderDetail();
                                    paymentOrderDetail.setId(Long.valueOf(((LinkedHashMap) advancePolicyTitleVOS.get(i)).get("id").toString()));
                                    paymentOrderDetail.setOrderId(Long.valueOf(((LinkedHashMap) advancePolicyTitleVOS.get(i)).get("orderId").toString()));
                                    if (null != ((LinkedHashMap) advancePolicyTitleVOS.get(i)).get("shipName")) {
                                        paymentOrderDetail.setShipName(((LinkedHashMap) advancePolicyTitleVOS.get(i)).get("shipName").toString());
                                    }
                                    if (null != ((LinkedHashMap) advancePolicyTitleVOS.get(i)).get("expectedLoadingDate")) {
                                        try {
                                            paymentOrderDetail.setRealityLoadingDate(sdf.parse(((LinkedHashMap) advancePolicyTitleVOS.get(i)).get("expectedLoadingDate").toString()));
                                        } catch (ParseException e) {
                                            throw new RuntimeException(e);
                                        }
                                    }
                                    if (null != ((LinkedHashMap) advancePolicyTitleVOS.get(i)).get("expectedLoadingPort")) {
                                        paymentOrderDetail.setExpectedLoadingPort(((LinkedHashMap) advancePolicyTitleVOS.get(i)).get("expectedLoadingPort").toString());
                                    }
                                    if (null != ((LinkedHashMap) advancePolicyTitleVOS.get(i)).get("expectedUnloadingPort")) {
                                        paymentOrderDetail.setExpectedUnloadingPort(((LinkedHashMap) advancePolicyTitleVOS.get(i)).get("expectedUnloadingPort").toString());
                                    }
                                    if (null != ((LinkedHashMap) advancePolicyTitleVOS.get(i)).get("estimateLoadVolume")) {
                                        paymentOrderDetail.setEstimateLoadVolume(new BigDecimal(((LinkedHashMap) advancePolicyTitleVOS.get(i)).get("estimateLoadVolume").toString()));
                                    }
                                    if (null != ((LinkedHashMap) advancePolicyTitleVOS.get(i)).get("estimateGoodsPrice")) {
                                        paymentOrderDetail.setEstimateGoodsPrice(new BigDecimal(((LinkedHashMap) advancePolicyTitleVOS.get(i)).get("estimateGoodsPrice").toString()));
                                    }
                                    if (null != ((LinkedHashMap) advancePolicyTitleVOS.get(i)).get("orderDetailRemark")) {
                                        paymentOrderDetail.setOrderDetailRemark(((LinkedHashMap) advancePolicyTitleVOS.get(i)).get("orderDetailRemark").toString());
                                    }
                                    orderDetailMapper.updateById(paymentOrderDetail);
                                }
                            }
                        }
                    }
                    //更新货险相关--实际保单信息集合列表
                    if (id.equals("a3")) {
                        if (null != ((LinkedHashMap) d).get("informations")) {
                            List actualPolicyTitleVOS = ((ArrayList) ((LinkedHashMap) d).get("informations"));
                            if (null != actualPolicyTitleVOS && actualPolicyTitleVOS.size() > 0) {
                                for (int i = 0; i < actualPolicyTitleVOS.size(); i++) {
                                    SpPaymentOrderDetail paymentOrderDetail = new SpPaymentOrderDetail();
                                    paymentOrderDetail.setId(Long.valueOf(((LinkedHashMap) actualPolicyTitleVOS.get(i)).get("id").toString()));
                                    paymentOrderDetail.setOrderId(Long.valueOf(((LinkedHashMap) actualPolicyTitleVOS.get(i)).get("orderId").toString()));
                                    if (null != ((LinkedHashMap) actualPolicyTitleVOS.get(i)).get("realityLoadingDate")) {
                                        try {
                                            paymentOrderDetail.setRealityLoadingDate(sdf.parse(((LinkedHashMap) actualPolicyTitleVOS.get(i)).get("realityLoadingDate").toString()));
                                        } catch (ParseException e) {
                                            throw new RuntimeException(e);
                                        }
                                    }
                                    if (null != ((LinkedHashMap) actualPolicyTitleVOS.get(i)).get("maxPeakValue")) {
                                        paymentOrderDetail.setMaxPeakValue(((LinkedHashMap) actualPolicyTitleVOS.get(i)).get("maxPeakValue").toString());
                                    }
                                    if (null != ((LinkedHashMap) actualPolicyTitleVOS.get(i)).get("unitPrice")) {
                                        paymentOrderDetail.setUnitPrice(new BigDecimal(((LinkedHashMap) actualPolicyTitleVOS.get(i)).get("unitPrice").toString()));
                                    }
                                    if (null != ((LinkedHashMap) actualPolicyTitleVOS.get(i)).get("sumInsure")) {
                                        paymentOrderDetail.setSumInsure(new BigDecimal(((LinkedHashMap) actualPolicyTitleVOS.get(i)).get("sumInsure").toString()));
                                    }
                                    if (null != ((LinkedHashMap) actualPolicyTitleVOS.get(i)).get("rate")) {
                                        paymentOrderDetail.setRate(new BigDecimal(((LinkedHashMap) actualPolicyTitleVOS.get(i)).get("rate").toString()));
                                    }
                                    if (null != ((LinkedHashMap) actualPolicyTitleVOS.get(i)).get("totalPremiumDollar")) {
                                        paymentOrderDetail.setTotalPremiumDollar(new BigDecimal(((LinkedHashMap) actualPolicyTitleVOS.get(i)).get("totalPremiumDollar").toString()));
                                    }
                                    if (null != ((LinkedHashMap) actualPolicyTitleVOS.get(i)).get("totalPremiumRmb")) {
                                        paymentOrderDetail.setTotalPremiumRmb(new BigDecimal(((LinkedHashMap) actualPolicyTitleVOS.get(i)).get("totalPremiumRmb").toString()));
                                    }
                                    orderDetailMapper.updateById(paymentOrderDetail);
                                }
                            }
                        }
                    }
                    //更新装载第三方计量费用/卸载第三方计量费用信息集合列表
                    if (id.equals("a4")) {
                        if (null != ((LinkedHashMap) d).get("informations")) {
                            List thirdPartyitleVOS = ((ArrayList) ((LinkedHashMap) d).get("informations"));
                            if (null != thirdPartyitleVOS && thirdPartyitleVOS.size() > 0) {
                                for (int i = 0; i < thirdPartyitleVOS.size(); i++) {
                                    SpPaymentOrderDetail paymentOrderDetail = new SpPaymentOrderDetail();
                                    paymentOrderDetail.setId(Long.valueOf(((LinkedHashMap) thirdPartyitleVOS.get(i)).get("id").toString()));
                                    paymentOrderDetail.setOrderId(Long.valueOf(((LinkedHashMap) thirdPartyitleVOS.get(i)).get("orderId").toString()));
                                    if (null != ((LinkedHashMap) thirdPartyitleVOS.get(i)).get("cnoocCorporation")) {
                                        paymentOrderDetail.setCnoocCorporation(((LinkedHashMap) thirdPartyitleVOS.get(i)).get("cnoocCorporation").toString());
                                    }
                                    if (null != ((LinkedHashMap) thirdPartyitleVOS.get(i)).get("shipName")) {
                                        paymentOrderDetail.setShipName(((LinkedHashMap) thirdPartyitleVOS.get(i)).get("shipName").toString());
                                    }
                                    if (null != ((LinkedHashMap) thirdPartyitleVOS.get(i)).get("expectedLoadingPort")) {
                                        paymentOrderDetail.setExpectedLoadingPort(((LinkedHashMap) thirdPartyitleVOS.get(i)).get("expectedLoadingPort").toString());
                                    }
                                    if (null != ((LinkedHashMap) thirdPartyitleVOS.get(i)).get("expectedUnloadingPort")) {
                                        paymentOrderDetail.setExpectedUnloadingPort(((LinkedHashMap) thirdPartyitleVOS.get(i)).get("expectedUnloadingPort").toString());
                                    }
                                    if (null != ((LinkedHashMap) thirdPartyitleVOS.get(i)).get("thirdPartyCorporation")) {
                                        paymentOrderDetail.setThirdPartyCorporation(((LinkedHashMap) thirdPartyitleVOS.get(i)).get("thirdPartyCorporation").toString());
                                    }
                                    if (null != ((LinkedHashMap) thirdPartyitleVOS.get(i)).get("inspectFee")) {
                                        paymentOrderDetail.setInspectFee(new BigDecimal(((LinkedHashMap) thirdPartyitleVOS.get(i)).get("inspectFee").toString()));
                                    }
                                    if (null != ((LinkedHashMap) thirdPartyitleVOS.get(i)).get("orderDetailRemark")) {
                                        paymentOrderDetail.setOrderDetailRemark(((LinkedHashMap) thirdPartyitleVOS.get(i)).get("orderDetailRemark").toString());
                                    }
                                    orderDetailMapper.updateById(paymentOrderDetail);
                                }
                            }
                        }
                    }
                    //更新装载船代尾款/卸载船代尾款
                    if(id.equals("a6")){
                        if (null != ((LinkedHashMap) d).get("informations")) {
                            List advanceChargesEndVOs = ((ArrayList) ((LinkedHashMap) d).get("informations"));
                            if (null != advanceChargesEndVOs && advanceChargesEndVOs.size() > 0) {
                                for (int i = 0; i < advanceChargesEndVOs.size(); i++) {
                                    SpPaymentOrderDetail paymentOrderDetail = new SpPaymentOrderDetail();
                                    paymentOrderDetail.setId(Long.valueOf(((LinkedHashMap) advanceChargesEndVOs.get(i)).get("id").toString()));
                                    paymentOrderDetail.setOrderId(Long.valueOf(((LinkedHashMap) advanceChargesEndVOs.get(i)).get("orderId").toString()));
                                    if (null != ((LinkedHashMap) advanceChargesEndVOs.get(i)).get("cnoocCorporation")) {
                                        paymentOrderDetail.setCnoocCorporation(((LinkedHashMap) advanceChargesEndVOs.get(i)).get("cnoocCorporation").toString());
                                    }
                                    if (null != ((LinkedHashMap) advanceChargesEndVOs.get(i)).get("shipAgencyCorporation")) {
                                        paymentOrderDetail.setShipAgencyCorporation(((LinkedHashMap) advanceChargesEndVOs.get(i)).get("shipAgencyCorporation").toString());
                                    }
                                    if (null != ((LinkedHashMap) advanceChargesEndVOs.get(i)).get("shipName")) {
                                        paymentOrderDetail.setShipName(((LinkedHashMap) advanceChargesEndVOs.get(i)).get("shipName").toString());
                                    }
                                    if (null != ((LinkedHashMap) advanceChargesEndVOs.get(i)).get("realityLoadingDate")) {
                                        try {
                                            paymentOrderDetail.setRealityLoadingDate(sdf.parse(((LinkedHashMap) advanceChargesEndVOs.get(i)).get("realityLoadingDate").toString()));
                                        } catch (ParseException e) {
                                            throw new RuntimeException(e);
                                        }
                                    }
                                    if (null != ((LinkedHashMap) advanceChargesEndVOs.get(i)).get("realityUnloadingDate")) {
                                        try {
                                            paymentOrderDetail.setRealityUnloadingDate(sdf.parse(((LinkedHashMap) advanceChargesEndVOs.get(i)).get("realityUnloadingDate").toString()));
                                        } catch (ParseException e) {
                                            throw new RuntimeException(e);
                                        }
                                    }
                                    if (null != ((LinkedHashMap) advanceChargesEndVOs.get(i)).get("expectedLoadingPort")) {
                                        paymentOrderDetail.setExpectedLoadingPort(((LinkedHashMap) advanceChargesEndVOs.get(i)).get("expectedLoadingPort").toString());
                                    }
                                    if (null != ((LinkedHashMap) advanceChargesEndVOs.get(i)).get("expectedUnloadingPort")) {
                                        paymentOrderDetail.setExpectedUnloadingPort(((LinkedHashMap) advanceChargesEndVOs.get(i)).get("expectedUnloadingPort").toString());
                                    }
                                    if (null != ((LinkedHashMap) advanceChargesEndVOs.get(i)).get("advancePayAmount")) {
                                        paymentOrderDetail.setAdvancePayAmount(new BigDecimal(((LinkedHashMap) advanceChargesEndVOs.get(i)).get("advancePayAmount").toString()));
                                    }
                                    if (null != ((LinkedHashMap) advanceChargesEndVOs.get(i)).get("balanceAmount")) {
                                        paymentOrderDetail.setBalanceAmount(new BigDecimal(((LinkedHashMap) advanceChargesEndVOs.get(i)).get("balanceAmount").toString()));
                                    }
                                    if (null != ((LinkedHashMap) advanceChargesEndVOs.get(i)).get("accountInitialBalance")) {
                                        paymentOrderDetail.setAccountInitialBalance(new BigDecimal(((LinkedHashMap) advanceChargesEndVOs.get(i)).get("accountInitialBalance").toString()));
                                    }
                                    if (null != ((LinkedHashMap) advanceChargesEndVOs.get(i)).get("paidAmount")) {
                                        paymentOrderDetail.setPaidAmount(new BigDecimal(((LinkedHashMap) advanceChargesEndVOs.get(i)).get("paidAmount").toString()));
                                    }
                                    if (null != ((LinkedHashMap) advanceChargesEndVOs.get(i)).get("accountBalance")) {
                                        paymentOrderDetail.setAccountBalance(new BigDecimal(((LinkedHashMap) advanceChargesEndVOs.get(i)).get("accountBalance").toString()));
                                    }
                                    orderDetailMapper.updateById(paymentOrderDetail);
                                }
                            }
                        }
                    }
                }
            });
        }
        //同步合同信息
        this.synchronousContract(paymentOrder);

        return paymentOrderDetailVO;
    }

    /**
     * 订单信息同步合同信息
     */
    public void synchronousContract(SpPaymentOrder spPaymentOrder) {
        PayFundManagement payFundManagement1 = payFundManagementMapper.selectOne(new LambdaQueryWrapper<PayFundManagement>()
                .eq(PayFundManagement::getOrderId, spPaymentOrder.getId())
        );
        if (null != payFundManagement1) {
            BeanUtils.copyProperties(spPaymentOrder, payFundManagement1);
            payFundManagementMapper.updateById(payFundManagement1);
        } else {
            PayFundManagement payFundManagement = new PayFundManagement();
            BeanUtils.copyProperties(spPaymentOrder, payFundManagement);
            payFundManagement.setId(IDUtil.nextId());
            payFundManagement.setAffiliatedContractId(spPaymentOrder.getContractId());
            payFundManagement.setCreateBy(SecurityUtils.getStringUserId());
            payFundManagement.setCreateDate(new Date());
            payFundManagement.setOrderId(spPaymentOrder.getId());
            payFundManagement.setPayOrderNumber(spPaymentOrder.getPayOrderNumber());
            payFundManagementMapper.insert(payFundManagement);
        }
    }

    /**
     * 同步订单详情信息到资金管理详情列表中
     */
    public void synchronousSpFundManageDetail(SpPaymentOrderDetail spPaymentOrderDetail, Long fundManageId, BigDecimal accountBalance) {
        SpFundManageDetail spFundManageDetail = new SpFundManageDetail();
        spFundManageDetail.setFundManageId(fundManageId);
        spFundManageDetail.setPayDate(new Date());
        SpPaymentOrder paymentOrder = this.getById(spPaymentOrderDetail.getOrderId());

        if (null != paymentOrder) {
            spFundManageDetail.setContractId(paymentOrder.getContractId());
            spFundManageDetail.setContractAddress(paymentOrder.getContractAddress());
            spFundManageDetail.setCorporateType(paymentOrder.getContractType());
            spFundManageDetail.setContractName(paymentOrder.getContractName());
            spFundManageDetail.setAccountInitialBalance(new BigDecimal(0));
            spFundManageDetail.setAccountEditBalance(new BigDecimal(0));
            //船舶代理合同信息
            if (null != paymentOrder.getContractType() && paymentOrder.getContractType().equals(1)) {
                spFundManageDetail.setCorporateType(CorporateType.SHIP_AGENCY_CORPORATION.getCode());
                ConShippingAgency shippingAgency = conShippingAgencyMapper.selectById(paymentOrder.getContractId());
                if (null != shippingAgency) {
                    spFundManageDetail.setCorporateName(shippingAgency.getCompanyName());
                    spFundManageDetail.setTradeBody(shippingAgency.getTradeBody());
                    spFundManageDetail.setSigningDate(shippingAgency.getSigningDate());
                    spFundManageDetail.setContractValidity(shippingAgency.getContractValidity());
                }
            }
            //第三方计量合同信息
            if (null != paymentOrder.getContractType() && paymentOrder.getContractType().equals(3)) {
                spFundManageDetail.setCorporateType(CorporateType.THIRD_PARTY_CORPORATION.getCode());
                ConThirdPartyMeasurement thirdPartyMeasurement = conThirdPartyMeasurementMapper.selectById(paymentOrder.getContractId());
                if (null != thirdPartyMeasurement) {
                    spFundManageDetail.setCorporateName(thirdPartyMeasurement.getPartyB());
                    spFundManageDetail.setTradeBody(thirdPartyMeasurement.getTradeBody());
                    spFundManageDetail.setSigningDate(thirdPartyMeasurement.getSigningDate());
                    spFundManageDetail.setContractValidity(thirdPartyMeasurement.getContractValidity());
                }
            }

            //同步账户余额（更新）
            spFundManageDetail.setAccountBalance(accountBalance);
            spFundManageDetail.setCreateDate(new Date());
            spFundManageDetail.setCreateBy(SecurityUtils.getUsername());
            spFundManageDetailMapper.insert(spFundManageDetail);
            Long id = spFundManageDetail.getId();

            //订单数量
            List<SpFundManageDetail> fundManageDetails = spFundManageDetailMapper.selectList(new LambdaQueryWrapper<SpFundManageDetail>()
                    .eq(SpFundManageDetail::getCorporateName, spFundManageDetail.getCorporateName())
                    .eq(SpFundManageDetail::getTradeBody, spFundManageDetail.getTradeBody())
            );
            Long num = fundManageDetails.stream().map(orderId -> orderId.getFundManageId()).distinct().count();
            spFundManageDetail.setOrderNumber(num.intValue());
            spFundManageDetailMapper.updateById(spFundManageDetail);
        }
    }

    /**
     * 同步订单信息到资金管理中
     */
    public SpFundManage synchronousSpFundManage(SpPaymentOrder paymentOrder, SpPaymentOrderDetail spPaymentOrderDetail) {
        logger.info("获取数据paymentOrder："+ JSONUtil.parse(paymentOrder) +"spPaymentOrderDetail:"+JSONUtil.parse(spPaymentOrderDetail));
        BigDecimal zero = BigDecimal.ZERO;
        SpFundManage fundManage = new SpFundManage();
        BeanUtils.copyProperties(paymentOrder, fundManage);
        fundManage.setId(IDUtil.nextId());

        fundManage.setShipName(spPaymentOrderDetail.getShipName());
        fundManage.setExpectedLoadingDate(spPaymentOrderDetail.getExpectedLoadingDate());
        fundManage.setExpectedUnloadingDate(spPaymentOrderDetail.getExpectedUnloadingDate());
        fundManage.setExpectedLoadingPort(spPaymentOrderDetail.getExpectedLoadingPort());
        fundManage.setExpectedUnloadingPort(spPaymentOrderDetail.getExpectedUnloadingPort());

        List<SpFundPayManageDetail> payManageDetailList = new ArrayList<>();
        //第三方计量
        if (null != paymentOrder.getContractType() && paymentOrder.getContractType().equals(3)) {
            //支付金额
            fundManage.setPayAmount(spPaymentOrderDetail.getInspectFee());

            SpFundManageDetail detail = spFundManageDetailMapper.selectOne(new LambdaQueryWrapper<SpFundManageDetail>()
                    .eq(StringUtils.isNotBlank(spPaymentOrderDetail.getCnoocCorporation())
                            , SpFundManageDetail::getCorporateName, spPaymentOrderDetail.getThirdPartyCorporation())
                    .orderByDesc(SpFundManageDetail::getCreateDate)
                    .last("LIMIT 1")
            );
            SpFundManage detailNew = null;
            if (detail != null) {
                detailNew = spFundManageMapper.selectById(detail.getFundManageId());
            }
            if (null != detailNew) {
                List<SpFundManage> fundManageList = spFundManageMapper.queryFundManageByCorporateName(detail.getCorporateName(),null);
                if (CollectionUtil.isNotEmpty(fundManageList)){
                    //计算用户总余额
                    List<QueryFundManageInfo> infoList = spFundPayManageDetailService.queryCountFundTotal(fundManageList);
                    if (CollectionUtil.isNotEmpty(infoList)){
                        BigDecimal fundTotal = new BigDecimal(0);
                        for (QueryFundManageInfo queryFundManageInfo : infoList) {
                            fundTotal = fundTotal.add(queryFundManageInfo.getAccountBalance());
                        }
                        //账户余额(初始)
                        fundManage.setAccountInitialBalance(fundTotal);
                        //待支付金额
                        BigDecimal payNumberTotal = fundManage.getPayAmount();
                        if (fundTotal.compareTo(fundManage.getPayAmount()) >= 0){
                            for (QueryFundManageInfo queryFundManageInfo : infoList) {
                                SpFundPayManageDetail spFundPayManageDetail = new SpFundPayManageDetail();
                                spFundPayManageDetail.setFundManageId(queryFundManageInfo.getId());
                                spFundPayManageDetail.setOrderId(spPaymentOrderDetail.getId());
                                if (queryFundManageInfo.getAccountBalance().compareTo(payNumberTotal) >= 0){
                                    spFundPayManageDetail.setPayNumber(payNumberTotal);
                                    //实付金额
                                    fundManage.setPaidAmount(BigDecimal.ZERO);
                                    //账户余额
                                    fundManage.setAccountBalance(fundTotal.subtract(fundManage.getPayAmount()));
                                    spFundPayManageDetail.setCreateTime(new Date());
                                    spFundPayManageDetail.setTradeBody(3);
                                    spFundPayManageDetail.setCorporateName(detail.getCorporateName());
                                    spFundPayManageDetail.setAccountBalance(fundTotal.subtract(fundManage.getPayAmount()));
                                    payManageDetailList.add(spFundPayManageDetail);
                                    break;
                                }else {
                                    fundTotal = fundTotal.subtract(queryFundManageInfo.getAccountBalance());
                                    payNumberTotal = payNumberTotal.subtract(queryFundManageInfo.getAccountBalance());
                                    spFundPayManageDetail.setPayNumber(queryFundManageInfo.getAccountBalance());
                                    spFundPayManageDetail.setCreateTime(new Date());
                                    spFundPayManageDetail.setTradeBody(3);
                                    spFundPayManageDetail.setCorporateName(detail.getCorporateName());
                                    spFundPayManageDetail.setAccountBalance(fundTotal);
                                    payManageDetailList.add(spFundPayManageDetail);
                                }
                            }
                        }else {
                            for (QueryFundManageInfo queryFundManageInfo : infoList) {
                                fundTotal = fundTotal.subtract(queryFundManageInfo.getAccountBalance());
                                SpFundPayManageDetail spFundPayManageDetail = new SpFundPayManageDetail();
                                spFundPayManageDetail.setFundManageId(queryFundManageInfo.getId());
                                spFundPayManageDetail.setOrderId(spPaymentOrderDetail.getId());
                                spFundPayManageDetail.setPayNumber(queryFundManageInfo.getAccountBalance());
                                spFundPayManageDetail.setCreateTime(new Date());
                                spFundPayManageDetail.setTradeBody(3);
                                spFundPayManageDetail.setCorporateName(detail.getCorporateName());
                                spFundPayManageDetail.setAccountBalance(fundTotal);
                                payManageDetailList.add(spFundPayManageDetail);
                            }
                            SpFundPayManageDetail spFundPayManageDetail = new SpFundPayManageDetail();
                            spFundPayManageDetail.setOrderId(spPaymentOrderDetail.getId());
                            spFundPayManageDetail.setPayNumber((fundManage.getPayAmount().subtract(fundManage.getAccountInitialBalance())).abs());
                            spFundPayManageDetail.setCreateTime(new Date());
                            spFundPayManageDetail.setTradeBody(3);
                            spFundPayManageDetail.setCorporateName(detail.getCorporateName());
                            spFundPayManageDetail.setAccountBalance(fundTotal);
                            payManageDetailList.add(spFundPayManageDetail);
                            //实付金额
                            fundManage.setPaidAmount(payNumberTotal.subtract(fundTotal));
                            //账户余额
                            fundManage.setAccountBalance(fundManage.getPayAmount().subtract(fundManage.getAccountInitialBalance()));
                        }
                    }
                }else {
                    //账户余额(初始)
                    fundManage.setAccountInitialBalance(detailNew.getAccountBalance());
                    SpFundPayManageDetail spFundPayManageDetail = new SpFundPayManageDetail();
                    spFundPayManageDetail.setOrderId(spPaymentOrderDetail.getId());


                    if (detailNew.getAccountBalance().compareTo(BigDecimal.ZERO) > 0){
                        //实付金额
                        fundManage.setPaidAmount(fundManage.getPayAmount().subtract(fundManage.getAccountInitialBalance()));
                        //账户余额
                        fundManage.setAccountBalance(detailNew.getAccountBalance().subtract(fundManage.getPayAmount()));
                        spFundPayManageDetail.setPayNumber(fundManage.getPayAmount().subtract(fundManage.getAccountInitialBalance()));
                        spFundPayManageDetail.setCreateTime(new Date());
                        spFundPayManageDetail.setTradeBody(3);
                        spFundPayManageDetail.setCorporateName(detail.getCorporateName());
                        spFundPayManageDetail.setAccountBalance(detailNew.getAccountBalance().subtract(fundManage.getPayAmount()));
                    }else {
                        fundManage.setPaidAmount(fundManage.getPayAmount());
                        //账户余额
                        fundManage.setAccountBalance((zero.subtract(fundManage.getPayAmount())).add(detailNew.getAccountBalance()));
                        spFundPayManageDetail.setPayNumber(fundManage.getPayAmount());
                        spFundPayManageDetail.setCreateTime(new Date());
                        spFundPayManageDetail.setTradeBody(3);
                        spFundPayManageDetail.setCorporateName(detail.getCorporateName());
                        spFundPayManageDetail.setAccountBalance((zero.subtract(fundManage.getPayAmount())).add(detailNew.getAccountBalance()));
                    }
                    payManageDetailList.add(spFundPayManageDetail);
                }

            } else {
                //账户余额(初始)
                fundManage.setAccountInitialBalance(zero);
                //实付金额
                fundManage.setPaidAmount(fundManage.getPayAmount().subtract(fundManage.getAccountInitialBalance()));
                //账户余额
                fundManage.setAccountBalance(zero.subtract(fundManage.getPaidAmount()));
            }
        }

        //船舶代理金额计算
        if (null != paymentOrder.getContractType() && paymentOrder.getContractType().equals(1)) {
            //支付金额
            fundManage.setPayAmount(paymentOrder.getPayAmount());

            Integer tradeBody = 0;
            ConShippingAgency shippingAgency = conShippingAgencyMapper.selectById(paymentOrder.getContractId());
            if (null != shippingAgency) {
                tradeBody = shippingAgency.getTradeBody();
            }

            //预付款并且状态为已支付
            if ((paymentOrder.getOrderType().equals(OrderType.LOADING_PORT_PAY.getCode()) || paymentOrder.getOrderType().equals(OrderType.UNLOADING_PORT_PAY.getCode()))
                    && paymentOrder.getOrderStatus().equals(OrderStatus.PAID.getCode())) {
                SpFundManage fundManageAdvance = spFundManageMapper.getFundManageAdvance(paymentOrder.getVoyageNo(), spPaymentOrderDetail.getShipAgencyCorporation(), tradeBody);

                fundManage.setVoyageNumber(1);
                fundManage.setPayAmount(spPaymentOrderDetail.getAdvancePayAmount());
                fundManage.setPaidAmount(spPaymentOrderDetail.getPaidAmount());
                fundManage.setAccountInitialBalance(BigDecimal.ZERO);

                SpFundPayManageDetail spFundPayManageDetail = new SpFundPayManageDetail();
                spFundPayManageDetail.setOrderId(spPaymentOrderDetail.getId());
                if (null != fundManageAdvance) {
                    fundManage.setAccountInitialBalance(fundManageAdvance.getAccountBalance());
                    if(fundManageAdvance.getVoyageNumber() != null){
                        fundManage.setVoyageNumber(fundManageAdvance.getVoyageNumber() + 1);
                    }
                }
                if(spPaymentOrderDetail.getBalanceAmount() != null){
                    //有账户结余，需要扣减金额
                    fundManage.setAccountBalance(fundManage.getAccountInitialBalance().subtract(spPaymentOrderDetail.getBalanceAmount()));
                }
                spFundPayManageDetail.setPayNumber(fundManage.getPayAmount());
                spFundPayManageDetail.setCreateTime(new Date())     ;
                spFundPayManageDetail.setTradeBody(tradeBody);
                spFundPayManageDetail.setCorporateName(spPaymentOrderDetail.getShipAgencyCorporation());
                spFundPayManageDetail.setAccountBalance(fundManage.getAccountBalance());
                payManageDetailList.add(spFundPayManageDetail);

//                List<SpFundManage> fundManageList = spFundManageMapper.queryFundManageByCorporateName(shippingAgency.getCompanyName(),tradeBody);
//                SpFundPayManageDetail spFundPayManageDetail1 = spFundManageMapper.getFundManageAdvanceAndEndNew(spPaymentOrderDetail.getShipAgencyCorporation(), tradeBody);
//
//                //fundManageAdvance为空，代表同公司，同贸易，同航次没有数据
//                if (null != fundManageAdvance) {
//                    fundManage.setVoyageNumber(fundManageAdvance.getVoyageNumber() + 1);
//                    //初始用户金额
//                    //fundManage.setAccountInitialBalance(fundManageAdvance.getAccountBalance());
//                } else {
//                    fundManage.setVoyageNumber(1);
//                    //初始用户金额
//                    // fundManage.setAccountInitialBalance(zero);
//                }
//                BigDecimal fundTotal = BigDecimal.ZERO;
//                if (null != spFundPayManageDetail1){
//                    fundTotal = spFundPayManageDetail1.getAccountBalance();
//                }
//                //初始金额
//                if (CollectionUtil.isNotEmpty(fundManageList)){
//                    List<QueryFundManageInfo> infoList = spFundPayManageDetailService.queryCountFundTotal(fundManageList);
//                    if (CollectionUtil.isNotEmpty(infoList)){
//                        BigDecimal payNumberTotal = fundManage.getPayAmount();
//
//                        //初始金额
//                        fundManage.setAccountInitialBalance(fundTotal);
//                        //计算实付金额
//                        if (fundTotal.compareTo(fundManage.getPayAmount()) >= 0){
//                            for (QueryFundManageInfo queryFundManageInfo : infoList) {
//                                SpFundPayManageDetail spFundPayManageDetail = new SpFundPayManageDetail();
//                                spFundPayManageDetail.setFundManageId(queryFundManageInfo.getId());
//                                spFundPayManageDetail.setOrderId(spPaymentOrderDetail.getId());
//                                if (queryFundManageInfo.getAccountBalance().compareTo(payNumberTotal) >= 0){
//                                    fundTotal = fundTotal.subtract(payNumberTotal);
//                                    spFundPayManageDetail.setPayNumber(payNumberTotal);
//                                    //实付金额
//                                    fundManage.setPaidAmount(BigDecimal.ZERO);
//                                    //账户余额
//                                    fundManage.setAccountBalance(fundManage.getAccountInitialBalance().subtract(fundManage.getPayAmount()));
//                                    spFundPayManageDetail.setCreateTime(new Date())     ;
//                                    spFundPayManageDetail.setTradeBody(tradeBody);
//                                    spFundPayManageDetail.setCorporateName(spPaymentOrderDetail.getShipAgencyCorporation());
//                                    spFundPayManageDetail.setAccountBalance(fundTotal);
//                                    payManageDetailList.add(spFundPayManageDetail);
//                                    break;
//                                }else {
//                                    fundTotal = fundTotal.subtract(queryFundManageInfo.getAccountBalance());
//                                    payNumberTotal = payNumberTotal.subtract(queryFundManageInfo.getAccountBalance());
//                                    spFundPayManageDetail.setPayNumber(queryFundManageInfo.getAccountBalance());
//                                    spFundPayManageDetail.setCreateTime(new Date());
//                                    spFundPayManageDetail.setTradeBody(tradeBody);
//                                    spFundPayManageDetail.setCorporateName(spPaymentOrderDetail.getShipAgencyCorporation());
//                                    spFundPayManageDetail.setAccountBalance(fundTotal);
//                                    payManageDetailList.add(spFundPayManageDetail);
//                                }
//                            }
//                        }else {
//                            for (QueryFundManageInfo queryFundManageInfo : infoList) {
//                                fundTotal = fundTotal.subtract(queryFundManageInfo.getAccountBalance());
//                                payNumberTotal = payNumberTotal.subtract(queryFundManageInfo.getAccountBalance());
//                                SpFundPayManageDetail spFundPayManageDetail = new SpFundPayManageDetail();
//                                spFundPayManageDetail.setFundManageId(queryFundManageInfo.getId());
//                                spFundPayManageDetail.setOrderId(spPaymentOrderDetail.getId());
//                                spFundPayManageDetail.setPayNumber(queryFundManageInfo.getAccountBalance());
//                                spFundPayManageDetail.setCreateTime(new Date());
//                                spFundPayManageDetail.setTradeBody(tradeBody);
//                                spFundPayManageDetail.setCorporateName(spPaymentOrderDetail.getShipAgencyCorporation());
//                                spFundPayManageDetail.setAccountBalance(fundTotal);
//                                payManageDetailList.add(spFundPayManageDetail);
//                            }
//                            //实付金额
//                            fundManage.setPaidAmount(payNumberTotal.subtract(fundTotal));
//                            //账户余额
//                            fundManage.setAccountBalance(zero.subtract(BigDecimal.ZERO));
//                            SpFundPayManageDetail spFundPayManageDetail = new SpFundPayManageDetail();
//                            spFundPayManageDetail.setOrderId(spPaymentOrderDetail.getId());
//                            spFundPayManageDetail.setPayNumber(fundManage.getPaidAmount());
//                            spFundPayManageDetail.setCreateTime(new Date());
//                            spFundPayManageDetail.setTradeBody(tradeBody);
//                            spFundPayManageDetail.setCorporateName(spPaymentOrderDetail.getShipAgencyCorporation());
//                            spFundPayManageDetail.setAccountBalance(BigDecimal.ZERO);
//                            payManageDetailList.add(spFundPayManageDetail);
//                        }
//
//                    }else {
//                        fundManage.setAccountInitialBalance(fundTotal);
//                        //实付金额
//                        BigDecimal paidAmount = fundManage.getAccountInitialBalance().subtract(fundManage.getPayAmount());
//                        if (paidAmount.compareTo(zero) > 0) {
//                            fundManage.setPaidAmount(BigDecimal.ZERO);
//                            fundManage.setAccountBalance(paidAmount);
//                        } else {
//                            fundManage.setPaidAmount(paidAmount.abs());
//                            fundManage.setAccountBalance(BigDecimal.ZERO);
//                        }
//                        //用户金额（更新）
////                        BigDecimal userAmountUpdate = fundManage.getAccountInitialBalance().add(fundManage.getPaidAmount()).subtract(fundManage.getPayAmount());
//
//                        SpFundPayManageDetail spFundPayManageDetail = new SpFundPayManageDetail();
//                        spFundPayManageDetail.setOrderId(spPaymentOrderDetail.getId());
//                        spFundPayManageDetail.setPayNumber(fundManage.getPaidAmount());
//                        spFundPayManageDetail.setCreateTime(new Date());
//                        spFundPayManageDetail.setTradeBody(tradeBody);
//                        spFundPayManageDetail.setCorporateName(spPaymentOrderDetail.getShipAgencyCorporation());
//                        spFundPayManageDetail.setAccountBalance(fundManage.getAccountBalance());
//                        payManageDetailList.add(spFundPayManageDetail);
//                    }
//
//                }else {
////                    if (fundManageAdvance2 != null) {
////                        fundManage.setAccountInitialBalance(fundManageAdvance2.getAccountBalance());
////                    } else {
////                        fundManage.setAccountInitialBalance(zero);
////                    }
//                    fundManage.setAccountInitialBalance(fundTotal);
//                    //实付金额
//
//                    BigDecimal paidAmount = fundManage.getAccountInitialBalance().subtract(fundManage.getPayAmount());
//                    if (paidAmount.compareTo(zero) > 0) {
//                        fundManage.setPaidAmount(BigDecimal.ZERO);
//                        fundManage.setAccountBalance(paidAmount);
//                    } else {
//                        fundManage.setPaidAmount(paidAmount.abs());
//                        fundManage.setAccountBalance(BigDecimal.ZERO);
//                    }
//                    //用户金额（更新）
////                    BigDecimal userAmountUpdate = fundManage.getAccountInitialBalance().add(fundManage.getPaidAmount()).subtract(fundManage.getPayAmount());
//                    SpFundPayManageDetail spFundPayManageDetail = new SpFundPayManageDetail();
//                    spFundPayManageDetail.setOrderId(spPaymentOrderDetail.getId());
//                    spFundPayManageDetail.setPayNumber(fundManage.getPaidAmount());
//                    spFundPayManageDetail.setCreateTime(new Date());
//                    spFundPayManageDetail.setTradeBody(tradeBody);
//                    spFundPayManageDetail.setCorporateName(spPaymentOrderDetail.getShipAgencyCorporation());
//                    spFundPayManageDetail.setAccountBalance(fundManage.getAccountBalance());
//                    payManageDetailList.add(spFundPayManageDetail);
//                }

            }

            //尾款
            if (paymentOrder.getOrderType().equals(LOADING_PORT_PAY_END.getCode()) || paymentOrder.getOrderType().equals(OrderType.UNLOADING_PORT_PAY_END.getCode())) {
                SpFundManage fundManageEnd = spFundManageMapper.getFundManageEnd(paymentOrder.getVoyageNo(), spPaymentOrderDetail.getShipAgencyCorporation(), tradeBody);
                SpFundManage fundManageEnd1 = spFundManageMapper.getFundManageAdvanceAndEnd(paymentOrder.getVoyageNo(), spPaymentOrderDetail.getShipAgencyCorporation(), tradeBody);
                List<SpFundManage> fundManageList = spFundManageMapper.queryFundManageByCorporateName(shippingAgency.getCompanyName(),tradeBody);
                SpFundPayManageDetail spFundPayManageDetail1 = spFundManageMapper.getFundManageAdvanceAndEndNew(spPaymentOrderDetail.getShipAgencyCorporation(), tradeBody);
                //fundManageEnd为空，代表同公司，同贸易，同航次没有数据
                if (null != fundManageEnd) {
                    fundManage.setVoyageNumber(fundManageEnd.getVoyageNumber() + 1);
                    //初始用户金额
                    //fundManage.setAccountInitialBalance(fundManageEnd.getAccountBalance());
                } else {
                    fundManage.setVoyageNumber(1);
                    //初始用户金额
                    //fundManage.setAccountInitialBalance(zero);
                }
                BigDecimal countFundTotal = BigDecimal.ZERO;
                //计算充值余额
                List<QueryFundManageInfo> infoList = new ArrayList<>();
                if (CollectionUtil.isNotEmpty(fundManageList)){
                    infoList = spFundPayManageDetailService.queryCountFundTotal(fundManageList);
//                    if (CollectionUtil.isNotEmpty(infoList)){
//                        for (QueryFundManageInfo queryFundManageInfo : infoList) {
//                            fundTotal = fundTotal.add(queryFundManageInfo.getAccountBalance());
//                        }
//                    }
                }


                if (spFundPayManageDetail1 != null) {
                    fundManage.setAccountInitialBalance(spFundPayManageDetail1.getAccountBalance());
                } else {
                    fundManage.setAccountInitialBalance(zero);
                }



//                //初始金额
//                if (fundManageEnd1 != null) {
//                    fundManage.setAccountInitialBalance(fundManageEnd1.getAccountBalance());
//                } else {
//                    fundManage.setAccountInitialBalance(zero);
//                }
                BigDecimal fundTotal = fundManage.getAccountInitialBalance();
                //获取到对应第几次的预付款信息
                SpFundManage fundManageAdvance = spFundManageMapper.getFundManageByVoyageNumber(paymentOrder.getVoyageNo(), spPaymentOrderDetail.getShipAgencyCorporation(), tradeBody, fundManage.getVoyageNumber());
                BigDecimal advanceAmount = BigDecimal.ZERO;
                if (null != fundManageAdvance) {
                    //支付金额
                    advanceAmount = fundManageAdvance.getPayAmount();
                }
                //实付金额
                BigDecimal paidAmount = BigDecimal.ZERO;
                //实际支付金额
                BigDecimal payAmount = advanceAmount.subtract(fundManage.getPayAmount());
                if (payAmount.compareTo(BigDecimal.ZERO) >= 0){
                    paidAmount = BigDecimal.ZERO;
                    fundManage.setPaidAmount(paidAmount);
                    SpFundPayManageDetail spFundPayManageDetail = new SpFundPayManageDetail();
                    spFundPayManageDetail.setOrderId(spPaymentOrderDetail.getId());
                    spFundPayManageDetail.setPayNumber(fundManage.getPayAmount());
                    spFundPayManageDetail.setCreateTime(new Date());
                    spFundPayManageDetail.setTradeBody(tradeBody);
                    spFundPayManageDetail.setCorporateName(spPaymentOrderDetail.getShipAgencyCorporation());
                    spFundPayManageDetail.setAccountBalance(fundTotal.add(payAmount));
                    payManageDetailList.add(spFundPayManageDetail);
                }else {
                    if (CollectionUtil.isNotEmpty(infoList)){
                        BigDecimal balanceAmount = payAmount.abs();
                        if (fundTotal.compareTo(payAmount.abs()) >= 0){
                            for (QueryFundManageInfo queryFundManageInfo : infoList) {
                                if (queryFundManageInfo.getAccountBalance().compareTo(balanceAmount) >= 0){
                                    SpFundPayManageDetail spFundPayManageDetail = new SpFundPayManageDetail();
                                    spFundPayManageDetail.setFundManageId(queryFundManageInfo.getId());
                                    spFundPayManageDetail.setOrderId(spPaymentOrderDetail.getId());
                                    spFundPayManageDetail.setPayNumber(balanceAmount);
                                    spFundPayManageDetail.setCreateTime(new Date());
                                    spFundPayManageDetail.setTradeBody(tradeBody);
                                    spFundPayManageDetail.setCorporateName(spPaymentOrderDetail.getShipAgencyCorporation());
                                    spFundPayManageDetail.setAccountBalance(fundTotal.subtract(balanceAmount));
                                    payManageDetailList.add(spFundPayManageDetail);
                                    break;
                                }else {
                                    fundTotal = fundTotal.subtract(queryFundManageInfo.getAccountBalance());
                                    balanceAmount = balanceAmount.subtract(queryFundManageInfo.getAccountBalance());
                                    SpFundPayManageDetail spFundPayManageDetail = new SpFundPayManageDetail();
                                    spFundPayManageDetail.setFundManageId(queryFundManageInfo.getId());
                                    spFundPayManageDetail.setOrderId(spPaymentOrderDetail.getId());
                                    spFundPayManageDetail.setPayNumber(queryFundManageInfo.getAccountBalance());
                                    spFundPayManageDetail.setCreateTime(new Date());
                                    spFundPayManageDetail.setTradeBody(tradeBody);
                                    spFundPayManageDetail.setCorporateName(spPaymentOrderDetail.getShipAgencyCorporation());
                                    spFundPayManageDetail.setAccountBalance(fundTotal.subtract(queryFundManageInfo.getAccountBalance()));
                                    payManageDetailList.add(spFundPayManageDetail);
                                }
                            }
                            fundManage.setPaidAmount(BigDecimal.ZERO);
                        }else {
                            for (QueryFundManageInfo queryFundManageInfo : infoList) {
                                SpFundPayManageDetail spFundPayManageDetail = new SpFundPayManageDetail();
                                spFundPayManageDetail.setFundManageId(queryFundManageInfo.getId());
                                spFundPayManageDetail.setOrderId(spPaymentOrderDetail.getId());
                                spFundPayManageDetail.setPayNumber(queryFundManageInfo.getAccountBalance());
                                spFundPayManageDetail.setCreateTime(new Date());
                                spFundPayManageDetail.setTradeBody(tradeBody);
                                spFundPayManageDetail.setCorporateName(spPaymentOrderDetail.getShipAgencyCorporation());
                                spFundPayManageDetail.setAccountBalance(fundTotal.subtract(queryFundManageInfo.getAccountBalance()));
                                payManageDetailList.add(spFundPayManageDetail);
                            }
                            fundManage.setPaidAmount(payAmount.abs().subtract(fundManage.getAccountInitialBalance()));
                            SpFundPayManageDetail spFundPayManageDetail = new SpFundPayManageDetail();
                            spFundPayManageDetail.setOrderId(spPaymentOrderDetail.getId());
                            spFundPayManageDetail.setPayNumber(payAmount.abs().subtract(fundManage.getAccountInitialBalance()));
                            spFundPayManageDetail.setCreateTime(new Date());
                            spFundPayManageDetail.setTradeBody(tradeBody);
                            spFundPayManageDetail.setCorporateName(spPaymentOrderDetail.getShipAgencyCorporation());
                            spFundPayManageDetail.setAccountBalance(BigDecimal.ZERO);
                            payManageDetailList.add(spFundPayManageDetail);
                        }
                    }else {
                        fundManage.setPaidAmount(payAmount.abs());
                        SpFundPayManageDetail spFundPayManageDetail = new SpFundPayManageDetail();
                        spFundPayManageDetail.setOrderId(spPaymentOrderDetail.getId());
                        spFundPayManageDetail.setPayNumber(payAmount.abs());
                        spFundPayManageDetail.setCreateTime(new Date());
                        spFundPayManageDetail.setTradeBody(tradeBody);
                        spFundPayManageDetail.setCorporateName(spPaymentOrderDetail.getShipAgencyCorporation());
                        spFundPayManageDetail.setAccountBalance(BigDecimal.ZERO);
                        payManageDetailList.add(spFundPayManageDetail);
                    }
                }

//                if (paidAmount.compareTo(zero) > 0) {
//                    fundManage.setPaidAmount(paidAmount);
//                } else {
//                    fundManage.setPaidAmount(paidAmount.abs());
//                }
                BigDecimal userAmountUpdate = BigDecimal.ZERO;
                //订单状态为已审核
                if (paymentOrder.getOrderStatus().equals(OrderStatus.AUDITE.getCode())) {
                    userAmountUpdate = fundManage.getAccountInitialBalance().add(advanceAmount).subtract(fundManage.getPayAmount());
                    //订单为已支付
                } else if (paymentOrder.getOrderStatus().equals(OrderStatus.PAID.getCode())) {
                    userAmountUpdate = fundManage.getAccountInitialBalance().add(fundManage.getPaidAmount());
                }
                if (userAmountUpdate.compareTo(BigDecimal.ZERO) > 0){
                    //用户金额（更新）
                    fundManage.setAccountBalance(userAmountUpdate);
                }else {
                    //用户金额（更新）
                    fundManage.setAccountBalance(BigDecimal.ZERO);
                }

            }
        }
        spPaymentOrderDetail.setPaidAmount(fundManage.getPaidAmount());
        spPaymentOrderDetail.setAccountInitialBalance(fundManage.getAccountInitialBalance());
        spPaymentOrderDetail.setAccountBalance(fundManage.getAccountBalance());
        if(spPaymentOrderDetail.getId()!=null){
            orderDetailMapper.updateById(spPaymentOrderDetail);
        }
        if (CollectionUtil.isNotEmpty(payManageDetailList)) {
            spFundPayManageDetailService.saveBatch(payManageDetailList);
        }
        fundManage.setCreateBy(SecurityUtils.getUsername());
        fundManage.setCreateDate(new Date());
        fundManage.setApplicantPeople(SecurityUtils.getUsername());
        spFundManageMapper.insert(fundManage);
        return fundManage;
    }
}
